0

With this code,

h = {}
for (var i in [0,1]){ h[i.ToString] = i; }

I expected same result with h["1"] = 1 and h["2"] = 2.

Why is this code doesn't work, and how can I define hash key dynamically in javascript?

1 Answer 1

1

The for .. in loop in JS iterates over keys, not over values (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in). So in your case, you iterate over the keys of the array you have in there.
Those will be 0, 1, 2 ... no matter what you put in there.

What you could do instead would be something like this:

var obj = {};
var data = [1,2,3,4];
data.forEach(function(val) {
    obj[val] = val;
});
Sign up to request clarification or add additional context in comments.

Comments

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.