JavaScript 属性访问:点符号与括号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4968406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript property access: dot notation vs. brackets?
提问by Mark Renouf
Other than the obvious fact that the first form could use a variable and not just a string literal, is there any reason to use one over the other, and if so under which cases?
除了第一种形式可以使用变量而不仅仅是字符串文字这一显而易见的事实之外,是否有任何理由使用一个而不是另一个,如果是这样,在哪些情况下?
In code:
在代码中:
// Given:
var foo = {'bar': 'baz'};
// Then
var x = foo['bar'];
// vs.
var x = foo.bar;
Context: I've written a code generator which produces these expressions and I'm wondering which is preferable.
上下文:我编写了一个生成这些表达式的代码生成器,我想知道哪个更可取。
回答by Aron Rotteveel
(Sourced from here.)
(来自这里。)
Square bracket notation allows the use of characters that can't be used with dot notation:
方括号表示法允许使用不能与点表示法一起使用的字符:
var foo = myForm.foo[]; // incorrect syntax var foo = myForm["foo[]"]; // correct syntax
var foo = myForm.foo[]; // incorrect syntax var foo = myForm["foo[]"]; // correct syntax
including non-ASCII (UTF-8) characters, as in myForm["ダ"]
(more examples).
包括非 ASCII (UTF-8) 字符,如myForm["ダ"]
(更多示例)。
Secondly, square bracket notation is useful when dealing with property names which vary in a predictable way:
其次,在处理以可预测方式变化的属性名称时,方括号表示法很有用:
for (var i = 0; i < 10; i++) { someFunction(myForm["myControlNumber" + i]); }
for (var i = 0; i < 10; i++) { someFunction(myForm["myControlNumber" + i]); }
Roundup:
围捕:
- 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
- 点符号写起来更快,读起来更清晰。
- 方括号表示法允许访问包含特殊字符的属性和使用变量选择属性
Another example of characters that can't be used with dot notation is property names that themselves contain a dot.
不能与点表示法一起使用的字符的另一个示例是本身包含点的属性名称。
For example a json response could contain a property called bar.Baz
.
例如,一个 json 响应可能包含一个名为bar.Baz
.
var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax
回答by naiquevin
The bracket notation allows you to access properties by name stored in a variable:
括号表示法允许您通过存储在变量中的名称访问属性:
var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello
obj.x
would not work in this case.
obj.x
在这种情况下不起作用。
回答by Sagar Munjal
The two most common ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x]
access a property on value—but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.
在 JavaScript 中访问属性的两种最常见方式是使用点和方括号。两者都value.x and value[x]
根据值访问一个属性——但不一定是相同的属性。不同之处在于 x 的解释方式。使用点时,点后的部分必须是有效的变量名,直接命名属性。使用方括号时,会计算方括号之间的表达式以获取属性名称。value.x 获取名为“x”的值的属性,而 value[x] 尝试计算表达式 x 并将结果用作属性名称。
So if you know that the property you are interested in is called “length”, you say value.length
. If you want to extract the property named by the value held in the variable i
, you say value[i]
. And because property names can be any string, if you want to access a property named “2”
or “John Doe”
, you must use square brackets: value[2] or value["John Doe"]
. This is the case even though you know the precise name of the property in advance, because neither “2” nor “John Doe”
is a valid variable name and so cannot be accessed through dot notation.
因此,如果您知道您感兴趣的属性称为“长度”,您会说value.length
。如果您想提取由保存在变量中的值命名的属性i
,您可以说value[i]
. 并且因为属性名称可以是任何字符串,所以如果要访问名为“2”
or的属性“John Doe”
,则必须使用方括号:value[2] or value["John Doe"]
。即使您事先知道属性的确切名称,情况也是如此,因为这两个“2” nor “John Doe”
名称都不是有效的变量名称,因此无法通过点表示法访问。
In case of Arrays
在数组的情况下
The elements in an array are stored in properties. Because the names of these properties are numbers and we often need to get their name from a variable, we have to use the bracket syntax to access them. The length property of an array tells us how many elements it contains. This property name is a valid variable name, and we know its name in advance, so to find the length of an array, you typically write array.length
because that is easier to write than array["length"]
.
数组中的元素存储在属性中。因为这些属性的名称是数字,我们经常需要从变量中获取它们的名称,所以我们必须使用括号语法来访问它们。数组的长度属性告诉我们它包含多少个元素。这个属性名是一个有效的变量名,我们事先知道它的名字,所以要找到一个数组的长度,你通常会写,array.length
因为它比 更容易写array["length"]
。
回答by Benjamin Crouzier
Dot notation does not work with some keywords (like new
and class
) in internet explorer 8.
点符号不适用于 Internet Explorer 8 中的某些关键字(如new
和class
)。
I had this code:
我有这个代码:
//app.users is a hash
app.users.new = {
// some code
}
And this triggers the dreaded "expected indentifier" (at least on IE8 on windows xp, I havn't tried other environments). The simple fix for that is to switch to bracket notation:
这会触发可怕的“预期标识符”(至少在 windows xp 上的 IE8 上,我还没有尝试过其他环境)。对此的简单解决方法是切换到括号表示法:
app.users['new'] = {
// some code
}
回答by user2593104
Be careful while using these notations: For eg. if we want to access a function present in the parent of a window. In IE :
使用这些符号时要小心:例如。如果我们想访问存在于窗口父级中的函数。在 IE 中:
window['parent']['func']
is not equivalent to
不等于
window.['parent.func']
We may either use:
我们可以使用:
window['parent']['func']
or
或者
window.parent.func
to access it
访问它
回答by CdB
Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like
一般来说,他们做同样的工作。
尽管如此,括号表示法让您有机会做点表示法无法做的事情,例如
var x = elem["foo[]"]; // can't do elem.foo[];
This can be extended to any property containing special characters.
这可以扩展到任何包含特殊字符的属性。
回答by álvaro González
You need to use brackets if the property names has special characters:
如果属性名称有特殊字符,则需要使用括号:
var foo = {
"Hello, world!": true,
}
foo["Hello, world!"] = false;
Other than that, I suppose it's just a matter of taste. IMHO, the dot notation is shorter and it makes it more obvious that it's a property rather than an array element (although of course JavaScript does not have associative arrays anyway).
除此之外,我想这只是一个品味问题。恕我直言,点符号更短,它更明显地表明它是一个属性而不是数组元素(尽管当然 JavaScript 无论如何都没有关联数组)。
回答by Lev Stefanovich
Bracket notation can use variables, so it is useful in two instances where dot notation will not work:
括号表示法可以使用变量,因此它在点表示法不起作用的两种情况下很有用:
1) When the property names are dynamically determined (when the exact names are not known until runtime).
1) 动态确定属性名称时(直到运行时才知道确切名称时)。
2) When using a for..in loop to go through all the properties of an object.
2) 当使用 for..in 循环遍历对象的所有属性时。
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
来源:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
回答by Harunur Rashid
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
属性名称是数字。
var ob = { 1: 'One', 7 : 'Seven' } ob.7 // SyntaxError ob[7] // "Seven"
属性名称具有特殊字符。
var ob = { 'This is one': 1, 'This is seven': 7, } ob.'This is one' // SyntaxError ob['This is one'] // 1
属性名称分配给一个变量,您希望通过该变量访问属性值。
var ob = { 'One': 1, 'Seven': 7, } var _Seven = 'Seven'; ob._Seven // undefined ob[_Seven] // 7
回答by Du?an Novák
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.
点符号总是更可取。如果您使用一些“更智能”的 IDE 或文本编辑器,它将显示该对象的未定义名称。仅当您的名称带有类似破折号或类似无效的名称时才使用方括号表示法。并且如果名称存储在变量中。