0

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.

3 Answers 3

4

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(...));
Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

-1

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));

3 Comments

I think you missed the location of the questionmark.
That was either to encourage improving/ deleting the answer. Now I'll take it back ;)
Initializing with zero (original question) is not the same as creating an empty object. Please revisit your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.