Benefit of using bracket notation (with variables)

2019-09-21 05:05发布

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.

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?

5条回答
该账号已被封号
2楼-- · 2019-09-21 05:19

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.

查看更多
狗以群分
3楼-- · 2019-09-21 05:23

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
查看更多
Fickle 薄情
4楼-- · 2019-09-21 05:24

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).

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

查看更多
爷的心禁止访问
5楼-- · 2019-09-21 05:30

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].

查看更多
Evening l夕情丶
6楼-- · 2019-09-21 05:43

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];
}
查看更多
登录 后发表回答