在JavaScript中查找数组的倾斜度
我们需要编写一个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