简体   繁体   中英

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:

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?

you can do it using a for loop

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

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. (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). 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]

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

And then

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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