difference between dot notation and bracket notation in javascript [duplicate]

牧云@^-^@ 提交于 2019-11-26 15:29:20
thefourtheye

When you use dot notation, key means the actual property in the object, which will not be there. So, undefined is returned which is not equal to true.

When you use [] notation you are accessing the property in the object with the name in the variable key. So, that will work.

For example,

var myObj = {
    myVar : 1
};

for (var key in myObj) {
    console.log(key);
    console.log(myObj.key);
    console.log(myObj[key]);
}

This will print,

myVar
undefined
1

Because, myObj has no member named key (myObj.key tries to get the member with the name key) and in the next case, myObj has a member named myVar (myObj[key] tries to get the member with the value in key).

Dot Notation

jslint prefers dot notation.

[] Notation

This offers flexibility. You can dynamically access the members with a variable.

Dot notation is faster to write and clearer to read.

Square bracket notation allows access to properties containing special characters and selection of properties using variables.

<form id="myForm">
<div><label>
<input type="checkbox" name="foo[]" value="1"> 1
</label></div>
<div><label>
<input type="checkbox" name="foo[]" value="2"> 2
</label></div>
<div><label>
<input type="checkbox" name="foo[]" value="3"> 3
</label></div>
</form>

Example with errors:

var inputs = myForm.foo[];

Square bracket notation, on the other hand, allows:

var inputs = myForm["foo[]"];

Since the square brackets are part of a string, their special meaning doesn't apply.The second advantage of square bracket notation is when dealing with variable property names.

for (var i = 0; i < 10; i++) {
doSomething(myForm["myControlNumber" + i]);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!