如何从数组中删除另一数组存在的元素?JS实现报错求助
代码问题分析与修复
第一段代码错误说明
- 循环终止条件缺少
.length属性:for (let i = 0; i < secondArray; i++)和for (let j = 0; j < secondRegex; j++)中,直接将数组对象和数字比较,判断结果永远为false,循环全程不会执行,因此输出空数组。
修复后代码
const secondRegex = ['i', 'a', 'about', 'am', 'an', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'how', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'what', 'when', 'where', 'who', 'will', 'with']; const secondArray = ['i', 'am','a', 'very', 'happy', 'child']; let myList = [] // 补充.length属性 for (let i = 0; i < secondArray.length; i++){ let is_the_same = 0; // 补充.length属性 for (let j = 0; j < secondRegex.length; j++){ if(secondArray[i] == secondRegex[j]){ is_the_same = 1; break; } } if (!is_the_same){ myList.push(secondArray[i]); } } console.log(myList); // 输出 ['very', 'happy', 'child']
第二段代码错误说明
- 作用域错误:
coincidence变量定义在for循环内部,循环外的if分支无法访问,会抛出变量未定义错误 - 逻辑错误:对整个
secondArray调用some方法,只要数组内有一个元素在secondRegex中,返回值永远为true,无法完成单个元素的校验 - 运算符错误:if判断中使用了赋值运算符
=而非比较运算符===,无论变量实际值是什么,判断结果永远为true,所有元素都会被跳过 - 语法结构错误:for循环的闭合大括号写在了逻辑判断之前,后续过滤逻辑不在循环体内,只会执行一次
修复后代码
const secondRegex = ['i', 'a', 'about', 'am', 'an', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'how', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'what', 'when', 'where', 'who', 'will', 'with']; const secondArray = ['i', 'am','a', 'very', 'happy', 'child']; let myList = [] for (let i = 0; i < secondArray.length; i++){ let value = secondArray[i]; // 直接判断当前元素是否在黑名单中 let coincidence = secondRegex.includes(value); // 把逻辑移到循环内部,用正确的比较运算符 if (coincidence === true){ continue; } else { myList.push(secondArray[i]); } } console.log(myList); // 输出 ['very', 'happy', 'child']
最简实现方案
直接使用数组的filter方法可以一行完成需求:
const myList = secondArray.filter(item => !secondRegex.includes(item))
内容的提问来源于stack exchange,提问作者In_need_of_help
相关产品推荐
相关产品推荐

