Home > Software design >  unexpected result when mapping two arrays with undefined values
unexpected result when mapping two arrays with undefined values

Time:07-31

Why does this map return different results when I apply it on two arrays that are supposed to be perfectly equal to each other?

let a = [1, 2, 3];
a.length = 7;
let b = [1, 2, 3, undefined, undefined, undefined, undefined];
console.log("a: "   a); //a: 1,2,3,,,,
console.log("b: "   b); //b: 1,2,3,,,,
console.log("It is "   a.every((x, i) => x === b[i])   " that these arrays are perfectly equal."); //It is true that these arrays are perfectly equal.
a = a.map(x => 1);
b = b.map(x => 1);
console.log("a: "   a); //a: 1,1,1,,,,
console.log("b: "   b); //b: 1,1,1,1,1,1,1

CodePudding user response:

Array a has 4-7 just as empty. In b 4-7 are undefined. After using the map function, that difference is showing up as "1,1,1,,,," and "1,1,1,1,1,1,1"

CodePudding user response:

These two arrays are not the same. pic

Due to this doc when you change the length of an array javascript injects "empty statement" in new indexes.

  • Related