簡體   English   中英

當數組存儲為全局變量時,增加數組索引不起作用

[英]Increasing index of array doesn't work when it's stored as global variable

我正在嘗試在函數 incIndex 運行時更新數組索引:

const arr=[1, 2, 3, 4, 5];
let index = 0;
let arrIndex = arr[index]
const incIndex = () => index++;

但它只能這樣工作

console.log(arr[index]) // 1
incIndex();
console.log(arr[index]) // 2

但是當我這樣做的時候

console.log(arrIndex) // 1
incIndex();
console.log(arrIndex) // 1

我仍然得到索引 0 的元素。有誰知道如何修復它以便我可以使用第二種方式?

你可以使用 for 循環來完成

const arr=[1, 2, 3, 4, 5];

for(let i = 0; i < arr.length; i++)
{
  console.log(arr[i]);
}

其中循環中的 i 變量將是遞增索引

你這樣做是不對的。

這個將數組的第一個元素的值復制到一個新變量。

let arrIndex = arr[index]

您不能指望它在更改索引時也會更改。

如果您在第一次聲明后不替換值, arrIndex值將始終相同。 (最后你還缺少分號)

如果您設置arrIndex = arr[index] ,它將等於您分配它時arr[index]的值 (1)。 它不是動態值。

對於動態值,您也許可以創建一個函數,但它不值得。 最好使用 arr[index]

function returnDynamicValue(){
    return arr[index];
}

接着

console.log(returnDynamicValue());
incIndex();
console.log(returnDynamicValue());

暫無
暫無

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

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