我从网络套接字中收到一条消息:
var message = {
spell: {
symbol: 'my-spell'
},
target: {
symbol: 'my-target'
}
};
我正在尝试学习解构,所以我编写了以下代码:
let {
spell: {
spell_symbol: symbol
},
target: {
target_symbol: symbol = null
}
} = message;
console.log('spell symbol: ' + spell_symbol);
console.log('target symbol: ' + target_symbol);
这给了我一个错误:
SyntaxError: Identifier 'symbol' has already been declared
我是否将语法写错了,还是不能在嵌套对象中重用symbol
之类的键?我将如何从target.symbol
中提取message
?
答案 0 :(得分:2)
您混合了属性名称和目标表达式的顺序,应该是
const {
spell: {
symbol: spell_symbol
},
target: {
symbol: target_symbol = null
}
} = message;
console.log('spell symbol: ' + spell_symbol);
console.log('target symbol: ' + target_symbol);