You simply have a misunderstanding of what Array.forEach
does:
progresses.forEach((item, i) => {
console.log(item); // [93,30,55]
console.log(speeds[i]); // [1,30, 5]
});
The first argument passed to you is the item itself.
The reason you cannot access the items of speed
is because you are asking for the 93rd item which does not exist so it returns undefined then you ask for speed[30]
which also does not exist so it is undefined then you ask for speed[55]
which again is undefined.
Follow-up
When iterating over processes array, how is console.log(speeds[i]) possible?
Your code works by accident. When using for..in the variable you get is the properties of an object. In older versions of javascript, depending on the interpreter the following code:
for(let i in speeds) {
console.log(progresses[i]);
}
Will get:
progress[0] // prints 93
progress[1] // prints 30
progress[2] // prints 55
progress['length'] // prints 3
progress['forEach'] // prints function
progress['map'] // prints function
.. etc
Newer versions of javascript made the change to array objects so that properties such as length
and forEach
are not enumerable
(I didn't know they changed this myself until this question).
You can test that this is what happens by giving the two arrays different length:
let progresses = [93,30,55];
let speeds = [1];
for(let i of speeds) {
console.log(progresses[i]); // [93]
}
In the code above the code only prints 93
instead of all three elements of the progress
array because the speed
array only has one element thus i
is only ever assigned the value 0
.
Note also that I am using for..of instead of for..in because for..of was designed to not return other properties of an array such as length
and forEach
. I know the current javascript does not do this with for..in but it's still a good idea to follow good practices since you can't really control what browser you users will use.