检查数组在JavaScript中是降序,升序还是未排序
我们需要编写一个包含数字数组的JavaScript函数。该函数应检查数组中的数字是按升序,降序还是无特定顺序。
如果数组仅包含一个元素,则应返回一条消息,指出元素不足。
如果数组中所有元素相等,我们应该返回一条消息,说所有元素均相等。
示例
为此的代码将是-
const arr1 = [7, 2, 1, 3, 2, 1];
const arr2 = [1, 1, 2, 3, 7, 7];
const determineOrder = arr => {
if(arr.length < 2){
return 'not enough items';
};
let ascending = null;
let nextArr = arr.slice(1);
for(var i = 0; i < nextArr.length; i++) {
if(nextArr[i] === arr[i]){
continue;
}else if(ascending === null) {
ascending = nextArr[i] > arr[i];
}else if (ascending !== nextArr[i] > arr[i]){
return 'unsorted';
};
}
if(ascending === null){
return 'all items are equal';
};
return ascending ? 'ascending' : 'descending';
};
console.log(determineOrder(arr1));
console.log(determineOrder(arr2));
console.log(determineOrder([1, 1, 1, 1]));
console.log(determineOrder([7, 2, 2, 1]));输出结果
控制台中的输出-
unsorted ascending all items are equal descending
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短