javascript - 数字数组中的任何一点是否有高程

标签 javascript arrays math

所以..我正在做一些事情,我需要知道一组有序的数字是否有任何“提升”,或者换句话说,不是按完全降序排列的。

如果我有 [3,2,1],它应该返回 false,而对于这些数字的任何其他顺序,它应该返回 true。例如。 [2,3,1],因为从左到右,海拔在 2 和 3 之间。

我使用以下小功能:

function hasElevation(digits) {
    return digits.slice().sort().reverse().toString() !== digits.toString();
}

我的问题是,是否有更有效的方法来做到这一点?

请使用 Vanilla JS!

更新:添加了用例

hasElevation([3,5,4]); // true
hasElevation([3,4,4]); // true
hasElevation([1]); // false
hasElevation([1,1]); // false
hasElevation([5,4,3]); // false

最佳答案

您可以使用 Array#some 查看对于每个元素和前一个元素。

function hasElevation(digits) {
    return digits.some(function (a, i, aa) {
        return aa[i - 1] < a;
    });
}

console.log(hasElevation([3, 5, 4])); // true
console.log(hasElevation([3, 4, 4])); // true
console.log(hasElevation([1]));       // false
console.log(hasElevation([1, 1]));    // false
console.log(hasElevation([5, 4, 3])); // false

ES6

var hasElevation = digits => digits.some((a, i, aa) => aa[i - 1] < a);

console.log(hasElevation([3, 5, 4])); // true
console.log(hasElevation([3, 4, 4])); // true
console.log(hasElevation([1]));       // false
console.log(hasElevation([1, 1]));    // false
console.log(hasElevation([5, 4, 3])); // false

关于javascript - 数字数组中的任何一点是否有高程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39267516/

相关文章:

math - 希尔伯特系统-自动打样

javascript - 如何在 JQuery 中捕获拖放事件?

php - 如何在 JavaScript 函数中使用 MySQL DB 数据?

javascript - vue-router匹配查询

c# - 如何在 C# 中将 IntPtr 转换为 Boolean[]?

c - 如何将一个变量的字符串分配给另一个变量?

c - 从 C 中的函数返回结构体数组

Javascript - 简单练习

javascript - HTML 数组上的淡入/淡出

math - float 学运算是否被破坏?