1

In javascript I can 'create' an associative array by initializing a javascript object via JSON

eg var bArr = {"key1": "val1","key2": "val2", "key3": "val3"}

then access the array elements like bArr["key1"], bArr["key2"], bArr["key3"].

However instead of initialization with JSON can we somehow just index elements like bArr["key1"] in a loop and assign them values individually ?

0

2 Answers 2

1

You can initialize values into your javascript object by doing bArr["key"] = "value";. Doing this will give you:

bArr = {
  "key": "value"
}

Thus, using a loop, you can concatenate i to the end of your key and value to generate your object which has keys from 1 to n and values from 1 to n, where n is an integer (of limited size):

var bArr = {};

for(var i = 1; i <= 3; i++) {
  bArr["key" +i] = "val" + i;
}

console.log(bArr);

Sign up to request clarification or add additional context in comments.

Comments

1

yes you can. very simple actually:

var obj = {};

for (var i = 0; i < 10; i++) {
  obj['val' + i] = i;
}

console.log(obj);

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.