Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables in dot notation like square bracket notation

Tags:

javascript

I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.

How would you do something like this in dot notation?

var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'
like image 534
Paul Sham Avatar asked Aug 18 '11 05:08

Paul Sham


2 Answers

You can't use variables in dot notation (short of using eval, which you don't want to do). With dot notation the property name is essentially a constant.

myObj.propName
// is equivalent to
myObj["propName"]
like image 62
nnnnnn Avatar answered Sep 28 '22 08:09

nnnnnn


You actually can now.

In this case you can use square brackets to use a variable for dot notation.

console.log(item.[x])

This is especially useful for use in Typescript.

like image 26
dwalter Avatar answered Sep 28 '22 08:09

dwalter