如何用JavaScript移除数组中的undefined值?遇filter方法异常
解决方案
1. 合并数组时自动过滤undefined值
你原来的合并方式会把数组中不存在的索引值(即undefined)直接转成字符串"undefined"拼接进去,正确的做法是先收集当前索引下的所有有效元素,过滤掉undefined后再拼接:
let arry1= ["txt", "txt2"]; let arry2= ["txt"]; let arry3= ["txt", "txt5", "txt6"]; // 改进后的合并代码 let c = arry1.map((value, index) => { // 收集当前索引的所有元素,过滤掉undefined const validItems = [value, arry2[index], arry3[index]].filter(item => item !== undefined); // 用空格拼接有效元素 return validItems.join(' '); }); // 输出结果:['txt txt txt', 'txt2 txt5'] console.log(c);
2. 清理已包含"undefined"子串的数组元素
对于已经生成的包含"undefined"字符串的数组,可以通过分割单词、过滤无效项、重新拼接的方式处理:
let a = ["undefined this", "that undefined ", "undefined value undefined"]; // 处理逻辑 let cleanedA = a.map(str => { return str.split(' ') // 过滤掉等于"undefined"的单词 .filter(word => word !== 'undefined') // 重新拼接成字符串 .join(' ') // 去除前后多余空格 .trim(); }); // 输出结果:["this", "that", "value"] console.log(cleanedA);
注意:你之前用
filter方法出错是因为filter是用来过滤数组元素的,而不是处理字符串内部的内容。上面的方案中,filter分别用来过滤数组元素(场景1)和分割后的单词数组(场景2),才是正确的用法。
内容的提问来源于stack exchange,提问作者Patrick Preston
相关产品推荐
相关产品推荐

