最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Benefit of using bracket notation (with variables) to access a property of an object - Stack Overflow

programmeradmin1浏览0评论

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 acplish the same task.

For example:

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

versus:

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?

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 acplish the same task.

For example:

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

versus:

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?

Share Improve this question edited Jan 18, 2017 at 23:51 Lukon asked Jan 18, 2017 at 23:35 LukonLukon 2651 gold badge7 silver badges20 bronze badges 1
  • Bracket syntax allows you to use dynamic property names – mhodges Commented Jan 18, 2017 at 23:36
Add a ment  | 

5 Answers 5

Reset to default 4

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 remended, but is doable).

For example:

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"])

One thing that distinguishes them is that with dot notation, you have to already know the property you want to access.

Consider the instance where you may want to obtain user input or some other external factor to decide what property to obtain:

function myFunction(property) {

    var data = {
        thingOne: "1",
        thingTwo: "2"
    }

    return data[property];
}

In the above function, one could not write return data.property - it would look for a property called property! You'd have to use index notation to get the correct value.

Bracket syntax is dynamic- It is typically used for collections, such as Lists, Arrays, Dictionaries, et cetera. Period notation is more useful for non-iterable fields, methods, and everything else you might want to access from a class.

For instance, you could iterate over a list with

var aggregate;
for (int i = 0; i < arrayOfNumbers.length; i++){
    aggregate += arrayOfNumbers[i];
}

It is usually based on preference, however I like to use bracket notation for arrays, and dot notation for objects. However if there is a property on the object with a dash in it, only bracket notation can be used.

foo = { "bar-baz": "value" };
foo["bar-baz"]; //returns "value"
foo.bar-baz; //error

The subscript syntax is more flexible than dot notation in a few ways. In your own example, performing some of the following operations is clearly impossible:

var playerNumber = 16;
var player = testObj.playerNumber; //null; this is equivalent to:
var player = testObj["playerNumber"]; //which is subscripting by the string "playerNumber"
var player = testObj[playerNumber]; //this is valid and produces the expected result: subscripting with the value 16

The dot notation is limited in that it cannot be used with variables holding dynamic values. testObj.playerNumber is not at all the same as testObj[playerNumber].

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论