You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JS every()方法判断数组升序时结果不符,求解答

问题分析与解决方案

核心问题

你的代码存在两个关键错误,导致结果不符合预期:

  • 箭头函数未显式返回值:你用大括号{}包裹了判断逻辑,但没有写return语句。这种情况下箭头函数会默认返回undefined,而every()方法会把undefined判定为false,直接导致最终结果异常。
  • 数组边界处理错误:当遍历到数组最后一个元素时,index + 1超出了数组索引范围,array[index + 1]的值为undefined。任何数值与undefined做<比较都会返回false,这直接破坏了整个判断逻辑。

修正后的代码

const testArray1 = [1, 2, 3, 4, 5, 6];
const testArray2 = [25, 51, 32, 12, 15];

const isAscending = (element, index, array) => {
  // 最后一个元素无需比较,直接返回true
  if (index === array.length - 1) {
    return true;
  }
  // 显式返回比较结果
  return element < array[index + 1];
};

console.log(testArray1.every(isAscending)); // 输出true
console.log(testArray2.every(isAscending)); // 输出false

也可以用更简洁的箭头函数写法(省略大括号时自动返回表达式结果):

const isAscending = (element, index, array) => 
  index === array.length - 1 ? true : element < array[index + 1];

修正说明

  1. 为箭头函数添加了显式的return语句,确保返回正确的布尔值给every()方法;
  2. 增加了边界判断,当遍历到最后一个元素时直接返回true——因为最后一个元素没有下一个元素需要比较,只要前面所有元素都符合升序条件,整个数组就是升序的。

内容的提问来源于stack exchange,提问作者RockyStrongo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 04:18:20