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);
}
produced the following output:
obj1
=> { '0': 1, '1': 1, '2': 1 }
and I would just kindly like to know why.
(I'm aware now that 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 output:
obj1
=> { '0': [ 0 ], '1': [ 1 ], '2': [ 2 ] }
)
[]is the same asArray.prototype, there is no empty array, and you're not pushing to anything insideobj. The second code snippet is the correct way of doing it, where you actually create an empty array