[英]javascript - potential infinite loop when comparing with arguments.length
我正在嘗試編寫一個遍歷函數所有輸入的for循環,比較輸入的元素,然后輸出唯一的元素(在這種情況下,它們始終是數字)。
由於這是一次freecodecamp練習 ,因此我得到了一些反饋,並收到以下錯誤: Error: potential infinite loop at line 4.
如果運行循環,而沒有無限循環保護,則內存不足。 有人可以指出我做錯了嗎?
function unite(arr1, arr2, arr3) {
//for all arrays
var output = arr1;
for(var x = 0; x < arguments.length; x++) {
for(var y = 0; y < arguments[x].length; y++) {
for(var i = 0; i < output.length; i++) {
if(arguments[x][y] !== output[i]) {
output.push(arguments[x][y]);
}
}
}
}
return output;
}
unite([1, 3, 2], [5, 2, 1, 4], [2, 1]);
我發現您的代碼有兩個問題。
1:在迭代數組時將其添加到數組中
您設置output = arr1', then start walking
arr1 as part of
參數的as part of
. Then you are adding items into
. Then you are adding items into
在循環中將. Then you are adding items into
arr1 / output`中。 將遍歷這些其他項目,並添加更多項目。
2:唯一測試存在缺陷
如果您確保output
數組中的項目唯一,則第一個問題可能還不錯。 不幸的是,您的輸出數組中的唯一性測試也存在問題。 當前項將添加到輸出數組中不匹配的每個條目。 如果您的輸出為[1,2,3,4]
,而您正在比較的項目為2
,則它將被壓入輸出3次,因為它與1、3或4不匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.