简体   繁体   English

当数组存储为全局变量时,增加数组索引不起作用

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

I'm trying to update array index as function incIndex runs:我正在尝试在函数 incIndex 运行时更新数组索引:

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

but it only works this way但它只能这样工作

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

but when I do但是当我这样做的时候

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

I still get element of index 0. Does anyone know how to fix it so I can use 2nd way?我仍然得到索引 0 的元素。有谁知道如何修复它以便我可以使用第二种方式?

you can do it using a for loop你可以使用 for 循环来完成

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

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

where the i variable in the loop would be the increasing index其中循环中的 i 变量将是递增索引

You are doing it wrong.你这样做是不对的。

This one copies the value of the first element of the array to a new variable.这个将数组的第一个元素的值复制到一个新变量。

let arrIndex = arr[index]

You can't expect it to be changed when changing the index.您不能指望它在更改索引时也会更改。

arrIndex value will be always the same if you don't replace the value after the first declaration.如果您在第一次声明后不替换值, arrIndex值将始终相同。 (Also you are missing a semicolon at the end) (最后你还缺少分号)

If you set arrIndex = arr[index] , it will be equal to the value of arr[index] at the moment you assign it (1).如果您设置arrIndex = arr[index] ,它将等于您分配它时arr[index]的值 (1)。 It is not a dynamic value.它不是动态值。

For a dynamic value you maybe can create a function but it doesn't worth it.对于动态值,您也许可以创建一个函数,但它不值得。 It's better to use arr[index]最好使用 arr[index]

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

And then接着

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM