简体   繁体   中英

Initializing Javascript Object at zero?

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.

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]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM