首页 > 不知是不是语言本身的bug

不知是不是语言本身的bug

先看代码:

var foo, bar;

foo = new Array(8);

bar = foo.map(function () {
  return 1;
});

// 注释一
console.dir(bar); // => [undefined × 8]

foo[6] = 1;

console.dir(foo); // => [undefined × 6, 1, undefined × 1]

bar = foo.map(function () {
  return 2;
});

console.dir(bar); // => [undefined × 6, 2, undefined × 1]

不知各位大神看出问题没有,可能是我“功夫”不到家,也许本来就没有问题。

我描述下问题:为什么注释一处,打印的结果不是[1, 1, 1, 1, 1, 1, 1, 1]?


 es5会跳过空位数组  es6不会 应该是这个原因  你可以参考一下

http://es6.ruanyifeng.com/#docs/array    搜素   数组的空位

foo = new Array(8);
foo.forEach(function(v, i) {
    console.log(v, i);
});
// 没有输出

foo[3] = 1;
foo.forEach(function(v, i) {
    console.log(v, i);
});
// 仅有一行输出:1 3

foo = [];
foo.length = 8;
foo.map(function() {
    return 1;
});
// [undefined x 8]

大概是跟 Array 的实现有关系。在 IE(我用的11) 上会有不同的效果。

【热门文章】
【热门文章】