Search code examples
javascriptprototypejs

why did the console'log had a attribute(length) , and this 'length' would not output in foreach?


Here is my code:

 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. 
 });

Any feedback is much appreciated.


Solution

  • Simply because the Array forEach method does only iterate indices (integer-named properties), not all properties. In fact it does need the .length property to know when to stop iterating :-)