在CodePen中使用巨大数组时出现奇怪的JavaScript行为
- 论坛
- 在CodePen中使用巨大数组时出现奇怪的JavaScript行为
5 浏览
在CodePen中使用巨大数组时出现奇怪的JavaScript行为
以下代码存在一个潜在的逻辑错误:
const arr = []; class Point{ constructor(){ this.x = Math.random() * 1000000; this.y = Math.random() * 1000000; } } console.time('foo'); let avg = 0; for(let i = 0; i < 114000000; i++ ){ arr.push(new Point()); avg += arr[i].x / 1000; } console.log(avg, arr.length); // 这不应该使得avg翻倍吗? for(let i = 0; i < 114000000; i++ ){ avg += arr[i].x / 1000; } console.log(avg, arr.length); console.timeEnd('foo');
CodePen - http://codepen.io/darkyen/pen/yOPMZg?editors=0010
可能的行为:
- 第二个for循环后,变量
avg
应该翻倍,数组的长度应该是1.14亿。 - 可能会出现内存错误。
作为脚本运行时的输出:
- 第二个for循环后,
avg
没有改变。 - 数组的长度不是1.14亿(Chrome 2-3M,Firefox Dev 5M,MS Edge 788k)。