-3

I have a object for which i am using push method and it gives me length one more than expected.

   var Object=[];
   var temp = {};
   var j=0;
   while(j<2){
      temp.id= j+1;
      //other properties setting

      Object.push(temp);
      j++;
  }

console.log(Object.length); 

gives me 3. Also I see three object values, first as empty second has id =1 and third has id =2.

user3421352
  • 101
  • 2
  • 4
  • 13

1 Answers1

2

.push is a function of Array and not Object and don't use variable names that cause ambiguity.

Use:

var arr = [];
var temp = {};
var j = 0;
while (j < 2) {
    temp.id = j + 1;
    //other properties setting

    arr.push(temp);
    j++;
}

console.log(arr.length);
Amit Joki
  • 58,320
  • 7
  • 77
  • 95