在 JavaScript 中查找数组的倾向性
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 4:28:17
我们需要编写一个 JavaScript 函数,该函数接受一个数字数组,如果数组严格增加或严格减少,则返回 true,否则返回 false。
在数学中,严格增加函数是要绘制的值始终增加的函数。同样,严格减少函数是要绘制的值始终减少的函数。
因此,让我们编写该函数的代码 −
示例
其代码为 −
const arr = [12, 45, 6, 4, 23, 23, 21, 1];
const arr2 = [12, 45, 67, 89, 123, 144, 2656, 5657];
const sameSlope = (a, b, c) => (b - a < 0 && c - b < 0) || (b - a > 0 && c - b > 0);
const increasingOrDecreasing = (arr = []) => {
if(arr.length <= 2){
return true;
};
for(let i = 1; i < arr.length - 1; i++){
if(sameSlope(arr[i-1], arr[i], arr[i+1])){
continue;
};
return false;
};
return true;
};
console.log(increasingOrDecreasing(arr));
console.log(increasingOrDecreasing(arr2));
输出
控制台中的输出将是 −
false true
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

