[V8] Holey Arrays

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

posted @   Zhentiw  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-11-13 [Spring Pattern] Builder pattern
2019-11-13 [Javascript] Check Promise is Promise
2019-11-13 [Javascript] Use requestIdleCallback to schedule JavaScript tasks at an optimal time
2019-11-13 [Javascript] Convert a callback based async operation into a Promise based
2017-11-13 [Python] String Formatting
2017-11-13 [TypeScript] Shallow copy object by using spread opreator
2017-11-13 [TypeScript] Model Alternatives with Discriminated Union Types in TypeScript
点击右上角即可分享
微信分享提示