Javascript: unexpected behavior, clicking on an empty array

The following code:

var arr1 = [1,2,3]; var obj1 = {}; for (var j = 0; j < arr1.length; j++) { if (obj1[j.toString()]) obj1[j.toString()] = obj1[j.toString()].push(j) else obj1[j.toString()] = [].push(j); } 

The following result appeared:

  obj1 => { '0': 1, '1': 1, '2': 1 } 

and I just wanted to know why.

(I now know the following code:

 var arr1 = [1,2,3]; var obj1 = {}; for (var j = 0; j < arr1.length; j++) { if (obj1[j.toString()]) obj1[j.toString()] = obj1[j.toString()].push(j) else { obj1[j.toString()] = []; obj1[j.toString()].push(j); } } 

will give me my desired result:

  obj1 => { '0': [ 0 ], '1': [ 1 ], '2': [ 2 ] } 

)

+5
source share
1 answer

Since from the documentation, the method Array.prototype.push() returns the length of the array, not the array itself.

+11
source

Source: https://habr.com/ru/post/1244318/


All Articles