Arrays are a list of references
An array element is a reference that is pointing to something (string literal, object, etc)
1 |
let arr = ['a', 'b', 'c', 'd']'; |
Array(4) [ "a", "b", "c", "d" ]
1 2 3 |
arr.forEach(function(cur){ cur = 'x'; }); |
Array(4) [ "a", "b", "c", "d" ]
Wuw what happened!?
So our array is a list of references that are pointing to the string literals.
When we use a callback function, the parameter of the callback function ‘cur’, is actually just a reference that happens to point to the string literals.
It does not re-point the array element reference. Hence, when we re-point the cur, it just points to ‘x’, and our arr (having nothing to do with cur) stays the same.
Grabbing those Array Elements
In order to re-point our array element references, we must access the array element reference itself.
1 2 3 |
arr.forEach(function(cur, index) { if (index < 3) arr[index] = 'x'; }); |
Array(4) [ "x", "x", "x", "d" ]
And now you have used arr[x] to access those reference themselves, you successfully re-point them to different string literals.
Objects can be manipulated
However, when we’re dealing with objects, we can use cur to manipulate it. This is because we’re not trying to re-point arr[x] to another object.
Rather, we’re just dereferencing the object itself, and changing its values.
1 2 3 4 5 |
let people = [{fname: 'kevin', lname: 'lee'}, {fname:'rick', lname: 'Vor'}]; people.forEach(function(cur){ cur.lname = 'Li'; }); |
0: Object { fname: "kevin", lname: "Li" }
1: Object { fname: "rick", lname: "Li" }
length: 2
es6
In es6, we can use from to create another array. Then use forEach to loop over it. For each person in the people array, we do the assignment.
1 |
Array.from(people).forEach(person => person.lname = 'Li'); |
Legal example
1 2 3 4 5 |
let ages = [24, 45, 35, 7, 7, 5, 3, 2]; let full = ages.map(function(cur) { return cur >= 18; }); |
(8) [true, true, true, false, false, false, false, false]
1 2 3 |
full.forEach(function(legal, index) { if (legal) console.log(`${ages[index]} is leeeegal ;)`); }); |
24 is leeeegal ;)
45 is leeeegal ;)
35 is leeeegal ;)