【发布时间】:2022-01-04 09:31:29
【问题描述】:
任务:创建一个函数,如果内部数组包含某个数字,则删除数组的外部元素。 IE filtersArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18) 应该返回 [[10, 8, 3], [14, 6, 23]]]
如果可能的话,我想解释一下导致此错误时代码到底在做什么/读取什么,而不是仅仅提供一个解决方案。
我已将我的思考过程作为注释包含在此代码中 - 所以希望如果我在某处有错误,可以指出。
function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
newArr = [...arr]; //copying the arr parameter to a new arr
for (let i=0; i< newArr.length; i++){ //iterating through out array
for (let x= 0; x< newArr[i].length; x++){ //iterating through inner array
if(arr[i][x] === elem){ //checking each element of the inner array to see if it matches the elem parameter
newArr.splice(i, 1); //if true, removing the entire outer array the elem is inside
}
}
}
// Only change code above this line
return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
【问题讨论】:
标签: javascript arrays typeerror