JS编写合并两数组提取数值元素函数返回空数组求助
combineArray函数返回空数组的问题原因及解决方法
问题原因
你的代码里犯了一个简单的拼写错误:循环条件中调用数组长度时写了newArr.lenght,而正确的数组长度属性名是length。
因为lenght不是数组的内置属性,所以newArr.lenght的值是undefined,循环条件i < undefined会被JavaScript隐式转换为i < NaN,这个判断结果永远是false,导致循环根本没有执行,用来存结果的numArr一直是空数组,最终返回空。
解决方法
1. 修复拼写错误的基础版本
把newArr.lenght改成newArr.length即可,修复后的代码如下:
function combineArray(arr1, arr2) { let numArr = []; let newArr = arr1.concat(arr2); for(let i = 0; i < newArr.length; i++){ if(typeof newArr[i] == "number") numArr.push(newArr[i]); } return numArr } let result = combineArray([12, "User01", 22, true, -8], ["Index", 6, null, 15]) console.log(result) // 输出 [12, 22, -8, 6, 15]
2. 更简洁的优化版本
可以利用数组的filter方法简化代码,一步完成合并和筛选:
function combineArray(arr1, arr2) { return arr1.concat(arr2).filter(item => typeof item === 'number'); } let result = combineArray([12, "User01", 22, true, -8], ["Index", 6, null, 15]) console.log(result) // 输出 [12, 22, -8, 6, 15]
内容的提问来源于stack exchange,提问作者Volodymyr
相关产品推荐
相关产品推荐

