Let's say we have an array like this:
let arr = ['a', 'b', 'c'];
Let's display the element with
the key 0
:
let arr = ['a', 'b', 'c'];
console.log(arr[0]); // shows 'a'
Let's now not write the key of the displayed element directly in square brackets, but write it into a variable:
let arr = ['a', 'b', 'c'];
let key = 0; // write the key to a variable
We now use our variable to display the corresponding element:
let arr = ['a', 'b', 'c'];
let key = 0; // write the key to a variable
console.log(arr[key]); // shows 'a'
Given the following array:
let arr = ['a', 'b', 'c'];
Also given the variable:
let key = 2;
Display the element whose key
is stored in the variable key
.
Given the following array:
let arr = [1, 2, 3, 4, 5];
Also given the variables:
let key1 = 1;
let key2 = 2;
Find the sum of elements whose keys are stored in our variables.