假设下面有一个代码块
function football(){
let options = {}
let [r, s, e] = ['Ronaldo', 'Messi', 'Aguero']
if(true){
options = {league: 'Premier League'}
[r, s, e] = ['Grealish', 'De Bruyne', 'Ramos']
console.log(options, r, s, e)
}
}
football()
此代码的输出为-['Grealish', 'De Bruyne', 'Ramos'] Ronaldo Messi Aguero
请指出在options
变量中没有; semicolon
时对象赋值不能工作的原因。
如果我们像这样在options = {league: 'Premier League'};
之后加上semicolon ;
,那么这将得到预期的输出-{league: 'Premier League'} Grealish De Bruyne Ramos
。
有谁能解释一下原因吗?Thanks in advance
如果没有分号这两行
options = {league: 'Premier League'}
[r, s, e] = ['Grealish', 'De Bruyne', 'Ramos']
被解释为单个表达式:
options = {league: 'Premier League'}[r, s, e] = ['Grealish', 'De Bruyne', 'Ramos']
{league: 'Premier League'}[r, s, e]
部分虽然有趣,但与此无关,因为返回值"的值总是被赋值的值:
let a = [];
let b = a[0] = 'first';
console.log(a, b);
// b = 'first' because the result of a[0] = 'first' is 'first'
因此你的代码相当于
options = ['Grealish', 'De Bruyne', 'Ramos']