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

如何在JavaScript数组中筛选特定范围值?我的代码存在什么问题?

问题分析与修复

你的代码存在两个关键问题:

  • 函数没有返回结果:inBetween函数内部创建了result数组并筛选出符合条件的元素,但最后没有通过return语句将这个数组返回,所以调用inBetween(arr)时得到的是undefined,自然看不到预期的[4,5]。
  • 函数未接收传入的参数:你调用inBetween(arr)时传入了数组,但函数定义时没有设置参数,而是直接使用全局的arr变量。虽然当前代码能运行(因为全局变量存在),但这种写法会降低函数的复用性,最好让函数接收参数,不依赖全局变量。

修正后的代码

基础修复(先解决核心问题)

let arr = [1, 2, 3, 4, 5, 6, 7];

function inBetween() {
  let result = [];
  for (let num of arr) {
    if (num > 3 && num < 6) {
      result.push(num);
    }
  }
  return result; // 新增返回语句
}

console.log(inBetween(arr)); // 现在会输出 [4,5]

优化版(接收参数,更健壮)

let arr = [1, 2, 3, 4, 5, 6, 7];

function inBetween(arr) { // 定义参数接收传入的数组
  let result = [];
  for (let num of arr) {
    if (num > 3 && num < 6) {
      result.push(num);
    }
  }
  return result;
}

console.log(inBetween(arr)); // 输出 [4,5]

更简洁的写法(使用数组的filter方法)

其实JavaScript数组自带filter方法,可以更简洁地实现这个需求:

let arr = [1, 2, 3, 4, 5, 6, 7];
const inBetween = arr => arr.filter(num => num > 3 && num < 6);
console.log(inBetween(arr)); // 输出 [4,5]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 21:25:06