如何在点符号中使用变量,如方括号表示法
问题描述:
我一直在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'
答
你可以' t使用点表示法中的变量(使用 eval
除外, 使用点表示法,属性名称基本上是常量。
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"]