0
JS - array: value becomes index ?
I do not understand the following case: a) x gets the value 2; but in arr[x] it becomes an index? Am I right with that? b) if i reuse x again, then it changes the value and not the index? I am confused. :-( Maybe someone out there can explain to me this, please.....? let x = 2; var arr = [4, 8, 16, 7, 41, 12]; console.log(arr); // output: [4, 8, 16, 7, 41, 12]; console.log(arr[x]); //output: 16 arr[x] = x + 1; console.log(arr[x]); // output: 3 arr[x] = x + 2; console.log(arr[x]); // output: 4 arr[x] = x + 3; console.log(arr[x]); // output: 5 console.log(arr); //output: [4, 8, 5, 7, 41, 12];
2 Answers
+ 1
let x = 2;
var arr = [4, 8, 16, 7, 41, 12];
// original array
console.log(arr); // output: [4, 8, 16, 7, 41, 12];
// arr[x] means arr[2] (third element) => 16
console.log(arr[x]); //output: 16
// modify arr[2] (third element)
// set its value to x + 1 (2 + 1) => 3
arr[x] = x + 1;
console.log(arr[x]); // output: 3
// modify arr[2] (third element)
// set its value to x + 2 (2 + 2) => 4
arr[x] = x + 2;
console.log(arr[x]); // output: 4
// modify arr[2] (third element)
// set its value to x + 3 (2 + 3) => 5
arr[x] = x + 3;
console.log(arr[x]); // output: 5
// the modified array
// this time the third element (index 2)
// has value 5
// due to the latest modification above
console.log(arr); //output: [4, 8, 5, 7, 41, 12];
+ 1
Thank you ! !
I was just irritated because x (as value) is outside the array.
So I thought as it is a value. But that it is at the same time the index, I did not know.