[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.prototype
to 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, .reduce
will 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
分类:
VM
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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