簡體   English   中英

JavaScript 調試挑戰

[英]JavaScript Debugging Challenge

根據議程,我應該得到以下輸出:

Element at 1 popped-out with value 10
Element at 2 popped-out with value 20
Element at 3 popped-out with value 30
Element at 4 popped-out with value 40
Element at 5 popped-out with value 50

但是,我低於輸出。

Element at 1 popped-out with value 10
Element at 2 popped-out with value 20
Element at 3 popped-out with value 30

下面是我試圖調試的 JavaScript。

 var writeMessage = function(i) { return document.write("Element at " + (i + 1) + " popped-out with value " + array.pop() + "<br />"); }; var array = [50, 40, 30, 20, 10]; for (var i = 0; i < array.length; i++) { writeMessage(i); }

我正在嘗試在 chrome 中調試。 循環執行引起了一些混亂。 任何人都可以幫我找到我做錯的地方嗎?

pop()從數組中刪除元素。

這使得數組更短。

這使得length的值更小。

i為 3 時,您將從數組中刪除 3 個元素,因此它不再是< array.length

您通過彈出值來縮短數組,因此每次迭代都會更改 array.length。 你可以同時循環它..

此外,在第一次迭代中,您正在播種最后一項。當i為零時,您將顯示第 6 個索引,當i為 5 時,您將顯示第一個索引。 這是因為pop()從數組中取出最后一個項目,您應該使用shift來從數組中取出第一個項目。

 var writeMessage = function(i) { return document.write("Element at " + (i) + " popped-out with value " + array.shift() + "<br />"); }; var array = [50, 40, 30, 20, 10], i; while (i = array.length) { writeMessage(i); }

或者您可以使用 for 循環並直接引用每個數組索引而不是更改數組。

 var writeMessage = function(i) { return document.write("Element at " + (array.length - i) + " popped-out with value " + array[i] + "<br />"); }; var array = [50, 40, 30, 20, 10]; for (var i = 0; i < array.length; i++) { writeMessage(i); }

當您調用array.pop() ,數組大小將減一。 這就是為什么只打印 3 個數字的原因。

這里的問題是,每次彈出數組的長度都會變短,並且在某個點(中間)增加的索引變得大於數組的長度。

迭代看起來像這樣

Initial state: array.length=5 i=0
1. if(i < array.length) pop & print (value=10)
2. array.length=4 i=1
3. if(i < array.length) pop & print (value=20)
4. array.length=3 i=2
5. if(i < array.length) pop & print (value=30)
6. array.length=2 i=3
7. if(i < array.length) <- here your iteration stops since the condition for the loop is false

i為 3 時,由於pop()減小其大小,數組的長度為 2,這意味着到達了 for 循環的端點。 將長度存儲在另一個變量中,您的代碼就可以工作了。 工作片段:

 var writeMessage = function(i) { return document.write("Element at " + (i + 1) + " popped-out with value " + array.pop() + "<br />"); }; var array = [50, 40, 30, 20, 10]; var l = array.length; for (var i = 0; i < l; i++) { writeMessage(i); }

簡單的邏輯。 我才發現,但晚了。 :-(

下面是邏輯:

<html>
<head>
<script type="text/javascript">
var writeMessage = function (i) {
    return document.write("Element at " + (i + 1) + " popped-out with value " + array.pop() + ". Now, the array length is: " + array.length + "<br />");
};

var array = [50, 40, 30, 20, 10];
for (var i = 0; array.length > 0; i++) {
    writeMessage(i);
}
</script>
</head>
<body>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM