除了第一种形式可以使用变量而不仅仅是字符串文字这一显而易见的事实之外,还有什么理由使用一个而不是另一个,如果是的话,在哪些情况下?
在代码中:
// Given:
var foo = {'bar': 'baz'};
// Then
var x = foo['bar'];
// vs.
var x = foo.bar;
上下文:我编写了一个代码生成器来生成这些表达式,我想知道哪个更可取。
除了第一种形式可以使用变量而不仅仅是字符串文字这一显而易见的事实之外,还有什么理由使用一个而不是另一个,如果是的话,在哪些情况下?
在代码中:
// Given:
var foo = {'bar': 'baz'};
// Then
var x = foo['bar'];
// vs.
var x = foo.bar;
上下文:我编写了一个代码生成器来生成这些表达式,我想知道哪个更可取。
(来自这里。)
方括号表示法允许使用点表示法不能使用的字符:
var foo = myForm.foo[]; // incorrect syntax var foo = myForm["foo[]"]; // correct syntax
包括非 ASCII (UTF-8) 字符,如myForm["ダ"]
(更多示例)。
其次,方括号符号在处理以可预测方式变化的属性名称时很有用:
for (var i = 0; i < 10; i++) { someFunction(myForm["myControlNumber" + i]); }
围捕:
- 点表示法写起来更快,读起来更清楚。
- 方括号表示法允许访问包含特殊字符的属性和使用变量选择属性
另一个不能与点表示法一起使用的字符示例是本身包含点的属性名称。
例如,一个 json 响应可能包含一个名为bar.Baz
.
var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax
括号表示法允许您按存储在变量中的名称访问属性:
var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello
obj.x
在这种情况下不起作用。
点表示法不适用于 Internet Explorer 8 中的某些关键字(如new
和class
)。
我有这个代码:
//app.users is a hash
app.users.new = {
// some code
}
这会触发可怕的“预期标识符”(至少在 windows xp 上的 IE8 上,我没有尝试过其他环境)。解决这个问题的简单方法是切换到括号表示法:
app.users['new'] = {
// some code
}
一般来说,他们做同样的工作。
尽管如此,括号符号让您有机会做点符号无法做到的事情,比如
var x = elem["foo[]"]; // can't do elem.foo[];
这可以扩展到任何包含特殊字符的属性。
使用这些符号时要小心:例如。如果我们想访问存在于窗口父级中的函数。在 IE 中:
window['parent']['func']
不等于
window.['parent.func']
我们可以使用:
window['parent']['func']
或者
window.parent.func
访问它
如果属性名称包含特殊字符,则需要使用括号:
var foo = {
"Hello, world!": true,
}
foo["Hello, world!"] = false;
除此之外,我想这只是一个品味问题。恕我直言,点表示法更短,它更明显地表明它是一个属性而不是数组元素(尽管 JavaScript 当然无论如何都没有关联数组)。
You have to use square bracket notation when -
The property name is number.
var ob = {
1: 'One',
7 : 'Seven'
}
ob.7 // SyntaxError
ob[7] // "Seven"
The property name has special character.
var ob = {
'This is one': 1,
'This is seven': 7,
}
ob.'This is one' // SyntaxError
ob['This is one'] // 1
The property name is assigned to a variable and you want to access the property value by this variable.
var ob = {
'One': 1,
'Seven': 7,
}
var _Seven = 'Seven';
ob._Seven // undefined
ob[_Seven] // 7
括号表示法可以使用变量,因此它在点表示法不起作用的两种情况下很有用:
1) 当属性名称是动态确定时(当直到运行时才知道确切的名称时)。
2) 当使用 for..in 循环遍历对象的所有属性时。
来源:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
[]
符号有用的情况:
如果您的对象是动态的,并且键中可能有一些随机值,例如number
and[]
或任何其他特殊字符,例如 -
var a = { 1 : 3 };
现在,如果您尝试a.1
通过错误进行访问,因为它期望那里有一个字符串。
Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object. Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.
让我添加更多方括号符号的用例。如果您想访问x-proxy
对象中的属性,那么-
将被错误地解释。它们还有一些其他情况,例如空格,点等,点操作对您没有帮助。此外,如果您在变量中有键,那么访问对象中键的值的唯一方法是通过括号表示法。希望你能得到更多的背景信息。
An example where the dot notation fails
json = {
"value:":4,
'help"':2,
"hello'":32,
"data+":2,
"":'',
"a[]":[
2,
2
]
};
// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json[""]);
console.log(json["a[]"]);
// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.);
console.log(json.a[]);
The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as
json.property_name
Or when you want to dynamically change the classList action for an element:
// Correct
showModal.forEach(node => {
node.addEventListener(
'click',
() => {
changeClass(findHidden, 'remove'); // Correct
},
true
);
});
//correct
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList[className]('hidden'));// Correct
}
}
// Incorrect
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList.className('hidden')); // Doesn't work
}
}