[V8] Holey Arrays

发布时间 2023-11-13 16:02:07作者: Zhentiw

What is holey array: an array with hole(s)

const array = [1,2, ,3]

Why this is a problem? Should array[2] to be undefined?

Yes and no.. normally it is undefined, but before that, VM has been check Array.prototypeto see Array.prototype["2"]whether it has value assigned or not. If not then VM set it to undefined, otherwise not.

(() => {
  const array = [1, 2, , 3];

  let sum = 0;
  for (let i = 0; i < array.length; i++) {
    const value = array[i];
    if (typeof value == "number") {
      sum += value;
    }
  }
  console.log("Sum:", sum); // 6
})();

 

Now try to mass up Array.prototype:

(() => {
  const array = [1, 2, , 3];
  Array.prototype["2"] = -3; // <-- this line

  let sum = 0;
  for (let i = 0; i < array.length; i++) {
    const value = array[i];
    if (typeof value == "number") {
      sum += value;
    }
  }
  console.log("Sum:", sum); // 3
})();

 

Is there any other way to create a holey array?

Yes: Array.from(10), once you create a holey array, then all the rest operation .map, .filter, .reducewill also build based on this holey array.

 

How to prevent that?

Array.from(10, (_el, _i) => 0) // give a defualt value when init the array