如何在点符号中使用变量,如方括号表示法 [英] How to use variables in dot notation like square bracket notation

查看:136
本文介绍了如何在点符号中使用变量,如方括号表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在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"]

这篇关于如何在点符号中使用变量,如方括号表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆