任務:創建一個函式,如果內部陣列包含某個數字,則洗掉陣列的外部元素。即filteredArray([[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));
uj5u.com熱心網友回復:
當您在最后一次迭代中找到該值時,您拆分外部陣列并仍然迭代內部陣列,但使用外部陣列的原始索引。通過縮小長度,它現在指向整個長度,任何嘗試使用undefined屬性訪問都會出錯。
為了克服這個問題并保持外部索引正確,您可以從最后一個索引開始并向后迭代。
除此之外,您可以打破內部搜索,因為在查找時,您不需要更多地迭代這個陣列。
uj5u.com熱心網友回復:
當您嘗試訪問變數的屬性時會發生此錯誤undefined。
你很可能是從你的線路上得到這個的:
for (let x= 0; x< newArr[i].length; x ){
如果您的引數arr不是陣列,newArr[0]則將是未定義的,因此 `newArr[0].lenght 將拋出此錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366737.html
標籤:javascript 数组 类型错误
上一篇:帶有陣列元素的For回圈內部函式。如何回傳函式輸出?
下一篇:語言統計
