js访问对象键值属性
Say you have this object:
说你有这个对象:
const dog = {
name : 'Roger'
}
To get the value of the name
property, you can use the dot syntax, like this:
要获取name
属性的值,可以使用点语法,如下所示:
dog . name
Or you can use the square brackets property accessor syntax:
或者,您可以使用方括号属性访问器语法:
dog [ 'name' ]
This is especially useful when a property has not a valid variable name, like the name
:
这是特别有用当一个属性没有一个有效的变量名,如the name
:
const dog = {
'the name' : 'Roger'
}
dog [ 'the name' ]
and it’s also very useful when you don’t know the property name beforehand, and you evaluate it programmatically, like in this example that loops through the object property names:
当您事先不知道属性名称并且以编程方式对其进行评估时,它也非常有用,例如在此示例中循环遍历对象属性名称:
const dog = {
'the name' : 'Roger'
}
for ( const [ key , value ] of Object. entries ( dog )) {
console . log ( value )
}
翻译自: https://flaviocopes.com/javascript-access-object-property/
js访问对象键值属性