rahul2001
rahul2001

Reputation: 1657

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.

Upvotes: 0

Views: 1928

Answers (3)

Todd
Todd

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

6502
6502

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

Amir Popovich
Amir Popovich

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

Related Questions