我今天才了解陣列,但我實際上并不了解我正在學習的這段代碼。
let units = [1, 10, 100, 1000, 20];
for(let i = 0; i < units.length; i = 1){
console.log(units[i]);
}
如何console.log(units[i]);回傳1, 10, 100, 1000,20和 not 5?
你們能向我解釋一下我將如何真正理解這一點嗎?
uj5u.com熱心網友回復:
units是一個陣列。
units[0]為您獲取陣列 (1) 中的第一項。units[1]為您獲取陣列中的下一項 (10)。等等。
因此,i隨著每次回圈迭代遞增,您從串列中獲取相應的專案。
uj5u.com熱心網友回復:
你都在宣告一個變數units存在并且你用你的陳述句將元素放入陣列中
let units = [1, 10, 100, 1000, 20];
這創建了一個包含 5 個元素的陣列;陣列元素從零開始編號(索引) :
| 1 | 10 | 100 | 1000 | 20 | // array with elements in it
0 1 2 3 4 // positions of elements
— 陣列中的第一個元素位于位置 0
,即位于的專案units[0]is 1,位于的專案units[1]is10等。
現在開始回圈,使用變數i作為數字作為陣列的索引。
當i === 0thenunits[i]請求 position 處的元素時units[0],即 1,then
時請求 position 處的元素,即 10,
依此類推。i === 1units[i]units[1]
所以當你說console.log(units[i]);你沒有列印i; 您正在獲取陣列中位于陣列中units位置的元素并列印它。when獲取陣列中位置 3 的專案,即,因此它列印 1000。i
console.log(units[i])i === 31000
uj5u.com熱心網友回復:
僅供您參考。
下面是變數中數字串列的初始化units
let units = [1, 10, 100, 1000, 20];
現在回圈開始。
for()是回圈。
第一個引數let i=0告訴陣列的起點。
第二個引數i<units.length定義了回圈需要結束的陣列的長度
3rs 引數告訴每次回圈執行時索引需要增加。例如:當 indexi為 0 時,則 value units[i] = 1。i由于i 作為for()回圈的第三個引數,在其執行后 index 的值增加了 1。
回圈將繼續,直到它滿足第二個引數中定義的最后一個索引的值,即i<units.length
for(let i = 0; i < units.length; i = 1){
console.log(units[i]);
}
我希望它讓你清楚。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/512371.html
下一篇:將值陣列傳遞給字串文本
