2 回答
TA贡献2012条经验 获得超12个赞
在 Javascript 中有多种访问对象的方法。
var myObj = {
variableOne: {
variableOneA: 'oneA',
variableOneB: 'oneB'
}
variableTwo: {
variableTwoA: 'twoA',
variableTwoB: 'twoB
}
variableThree: {
variableThreeA: 'threeA',
variableThreeB: 'threeB'
}
}
您可以使用“点”来访问对象的特定级别。
const valueVariableOneA = myObj.variableOne.variableOneA
console.log(valueVariableOneA) // output => "oneA"
您可以使用方括号代替点。当您想用破折号创建对象的键时,方括号很有用(例如:“cool-key”)
const valueVariableThreeB = myObj['variableThree']['variableThreeB']
console.log(valueVariableThreeB) // output => "threeB"
您还可以使用解构来访问特定值
// Get value of variableTwoA key
const { variableTwoA } = myObj.variableTwo // first way
const { variableTwo : { variableTwoA } } = myObj // second way
console.log(variableTwoA) // output => "twoA"
现在要向嵌套对象添加键,您可以使用点或方括号方法。这是在第一级添加密钥的方法。
myObj.variableFour = { variableFourA: 'fourA', variableFourB: 'fourB' }
myObj['variableFour'] = { variableFourA: 'fourA', variableFourB: 'fourB' }
// add key on nested object
myObj.variableOne.variableOneC = 'oneC'
myObj['variableOne']['variableOneC'] = 'oneC'
// you can mix both
myObj['variableOne'].variableOneC = 'oneC'
myObj.variableOne['variableOneC'] = 'oneC'
添加回答
举报