0

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.

stepbystep
  • 331
  • 1
  • 2
  • 8

3 Answers3

2

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');
Schlaus
  • 18,144
  • 10
  • 36
  • 64
  • It's inside a function. I tried window.nameOfFunction but that doesn't work. Also can you explain what is that you did? How come you used [] for 'b'+1? – stepbystep Feb 04 '17 at 20:43
  • @stepbystep I've updated my answer. Basically, you can access any property of an object by putting the name inside brackets. Also note that property names are always strings, so `window['1']` and `window[1]` refer to the same property. – Schlaus Feb 04 '17 at 21:52
1

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.

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
0

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"
blex
  • 24,941
  • 5
  • 39
  • 72