Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

关于ES6数组解构赋值的问题

这是阮一峰老师的ES6入门书里的代码,利用数组的解构赋值特性交换两个变量的值

let x = 1;
let y = 2;

[x, y] = [y, x]; 

以上代码确实在编辑器里能跑通,但是我试了下把分号去掉,浏览器报了y没有初始化的错误,这是为什么呢?

let x = 1
let y = 2

[x, y] = [y, x]

image.png

好像是引擎认为 let y = 2[x, y] = [y, x] 是同一个语句,我在第14行的断点打不下去,但是为什么是这样解析的呢。。
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

不写分号 js会解析成

var x = 1;
var y = 2[(x, y)] = [y, x];

y未赋值已被引用,所以报错~
Babel 编译


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...