Reputation: 1657
Is there a way to initialize a object with zero the way you can initialize a hash in ruby with 0 value?
Hash.new(0)...Object.create(0)?
I am trying to itterate thru an array and add each element as a key and increment the values.
Upvotes: 0
Views: 1928
Reputation: 5454
if you're trying to create an empty object you can just:
var obj = {};
Here's some stuff that wasn't asked for to deter downvotes
var obj = {};
['Lorem', 'ipsum', 'dolor', 'sit', 'amet,',
'consectetur', 'adipisicing', 'elit.', 'Enim',
'nam', 'aperiam,', 'doloribus', 'dolor', 'ullam',
'corrupti', 'aliquid', 'Magni', 'consequuntur',
'velit', 'consectetur', 'autem', 'sit', 'sint',
'temporibus', 'inventore'].forEach(function(a, i) {
obj[a] = i;
});
console.log(JSON.stringify(obj, null, 4));
Upvotes: -1
Reputation: 114559
No.
But you can do things like
tab[key] = (tab[key] || 0) + 1;
Having a default value would be slightly nicer but it wouldn't work when the default needs to be an expression to be evaluated only if needed.
With this pattern instead you can easily do things like
return cache[key] || (cache[key] = new Machine(...));
Upvotes: 4
Reputation: 29846
You can always create an Array
with a default value using apply
and map
:
var arrSize = 10;
var arr = Array.apply(null, new Array(arrSize)).map(Number.prototype.valueOf,0);
console.log(arr); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Upvotes: 2