使用括号表示法(带有变量)访问对象属性的好处 [英] Benefit of using bracket notation (with variables) to access a property of an object

查看:49
本文介绍了使用括号表示法(带有变量)访问对象属性的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然在需要访问一些存储的信息时使用点运算符之类的替代方法很有意义,但我在理解为什么以及在什么情况下使用变量来完成相同任务时遇到了一点困难.

While utilizing alternatives such as the dot operator make sense when needing to access some stored information, I'm having a little bit of difficulty understanding why and in what scenarios we would use variables to accomplish the same task.

例如:

var myObj = {
  prop1: "val1",
  prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2

与之相对:

var testObj = {

  12: "Namath",
  16: "Montana",
  19: "Unitas"
};

var playerNumber = 16;      
var player = testObj[playerNumber];

这仅仅是偏好设置的问题,还是使用它们各自有实际的好处吗?

Is it simply a matter of preference, or are there actual benefits to using each?

推荐答案

使用括号语法可以动态访问属性名称,而使用点语法则不能.这是一个如何使用它的示例:

Bracket syntax allows you to dynamically access property names, whereas dot syntax does not. Here is an example of how it could be used:

var data = {
  prop1: "I am prop 1",
  prop2: "I am prop 2"
};
function clickHandler () {
  var prop = this.getAttribute("data-property");
  console.log(data[prop]); // <-- Dynamically access object properties with [] syntax
}

var buttons = document.querySelectorAll("[data-property]");
for (var i = 0; i < buttons.length; i++) {
  var button = buttons[i];
  button.addEventListener("click", clickHandler);
}

<button data-property="prop1">Get Prop 1</button>
<button data-property="prop2">Get Prop 2</button>

括号语法还使您能够使用对象属性,这些对象属性否则为无效的变量名(不建议使用,但可行).

Bracket syntax also allows you the ability to use object properties that are otherwise invalid variable names (which is not recommended, but is doable).

例如:

var data = {
  "property name with spaces": "I'm a property with spaces",
  "another-invalid-variable-name": "I'm an invalid variable name"
};
console.log(data["property name with spaces"])
console.log(data["another-invalid-variable-name"])

这篇关于使用括号表示法(带有变量)访问对象属性的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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