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.
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(...));
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.