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

JavaScript中splice()方法过滤非数字失效,我遗漏了什么?

问题根因

你在正序遍历数组的同时调用splice修改原数组,会触发数组元素的自动补位:当你删除索引i位置的元素后,原本位于i+1位置的元素会前移到i的位置,下一轮循环i自增1,就会直接跳过这个补位上来的元素,导致部分非数字值没有被判断过滤。

解决方案

方案1:倒序遍历数组

从数组尾部往前遍历,删除元素时只会影响已经遍历过的后面的索引,不会干扰还未遍历的前序元素:

const arr = [3, 9, NaN, false, 13, -10, false, 17, 14, 9, 5, true, "error", true, false, "error", false];

for (let i = arr.length - 1; i >= 0; i--) {
  if (typeof arr[i] !== "number" || isNaN(arr[i]))
    arr.splice(i, 1);
}

console.log(arr); // 输出:[3, 9, 13, -10, 17, 14, 9, 5]

方案2:使用filter方法生成新数组(更推荐)

无需修改原数组,代码逻辑更简洁,不存在索引偏移问题:

const arr = [3, 9, NaN, false, 13, -10, false, 17, 14, 9, 5, true, "error", true, false, "error", false];
const validNumberArr = arr.filter(item => typeof item === "number" && !isNaN(item));
console.log(validNumberArr); // 输出:[3, 9, 13, -10, 17, 14, 9, 5]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:36:00