If I have:
var b1 = ["B", "V"];
I can access "V"
with b1[1]
;
Why does the following not work:
console.log(("b"+1)[1]);
I get 1 in console.
If I have:
var b1 = ["B", "V"];
I can access "V"
with b1[1]
;
Why does the following not work:
console.log(("b"+1)[1]);
I get 1 in console.
If b1
is defined in the global scope, you can access it as a member of the window object:
// When variable is defined in global scope
var b1 = ["B", "V"];
console.log(window['b'+1][1]);
// Inside a function you're stuck with eval.
// You should be really, really careful with eval.
// Most likely you can change your design so you wont need it.
function test() {
var b2 = ["B", "V"];
console.log(eval(('b'+1))[1]);
}
test();
// Just to demonstrate that accessing an object's properties
// always works the same way
window['console']['log']('hi');
You get 1 in console because "b"+1
is formatted to string to "b1"
. Index 1 in this string is character 1
.
Doing something you want is very bad idea. If you want to access these variables using numbers from other calls, use arrays b = []
and then use b[index][subindex]` for your string.
Or use window
scope variable.
Why you get that result
When you concatenate (+
) a String and a number, you get a String. Using the bracket notation on a String will get you the character at a certain index. In your case, "1"
.
How you can make it work
If your b1
variable is global (not defined inside a function), it is a property of window
. So you can access it using window["b"+1]
.
var b1 = ["B", "V"];
console.log( window["b"+1][1] ); // "V"
If it's local (inside of a function), use an Object to store it:
var scope = {};
scope.b1 = ["B", "V"];
console.log( scope["b"+1][1] ); // "V"