为什么控制台的日志有一个属性(长度),而这个 'length' 不会在 foreach 中输出?
why did the console'log had a attribute(length) , and this 'length' would not output in foreach?
这是我的代码:
var obj = {}; [].push.call(obj, "a");
console.log(obj);
//output:{0:"a",length:1} what length?
[].forEach.call(obj, function(v, i, a) {
console.log(i);
//output: 0
//Although this obj had two attributes, but only echoed once.
});
非常感谢任何反馈。
仅仅是因为 Array forEach
method 只迭代索引(整数命名的属性),而不是所有属性。事实上,它确实需要 .length
属性 来知道 何时停止迭代 :-)
这是我的代码:
var obj = {}; [].push.call(obj, "a");
console.log(obj);
//output:{0:"a",length:1} what length?
[].forEach.call(obj, function(v, i, a) {
console.log(i);
//output: 0
//Although this obj had two attributes, but only echoed once.
});
非常感谢任何反馈。
仅仅是因为 Array forEach
method 只迭代索引(整数命名的属性),而不是所有属性。事实上,它确实需要 .length
属性 来知道 何时停止迭代 :-)