Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js分号的问题 #5

Open
xiaohesong opened this issue Jan 30, 2019 · 0 comments
Open

js分号的问题 #5

xiaohesong opened this issue Jan 30, 2019 · 0 comments

Comments

@xiaohesong
Copy link
Owner

前言:对于前端到底要不要写分号,各有各的说法,我反正是没有这个习惯。然后,等被坑了之后,我有些话想说。

事情是这样的,在群里看到有人发了一段代码:

function * fibs(){
    let a = 0;
    let b = 1;
    while(true){
        yield a;
        [a, b] = [b, a + b];
    }
}
[first, second, third, fourth, fifth, sixth] = fibs()
sixth // 5

他的问题是这段代码怎么解读,不会死吗?当然,我看到这段代码是好奇最后的数组解构赋值的结果。如果这段代码正常工作,那么就验证了我的猜想。试着动动手的心态去试了下:

function * fibs(){
    let a = 0, b = 1;
    while(true){
        yield a;
        [a, b] = [b, a + b]
    }
}
[first, second, third, fourth, fifth, sixth] = fibs()
sixth//[1, 1]

咦,这什么鬼,为什么不一样?

然后,苦苦寻觅,越是尝试越是崩溃,不行,我得按照原图中的写一遍:

function * fibs(){
    let a = 0;
    let b = 1;
    while(true){
        yield a;
        [a, b] = [b, a + b];
    }
}
[first, second, third, fourth, fifth, sixth] = fibs()
sixth // 5

我想你也知道了,就是因为这个分号导致的结果不同。

解决了这个问题之后,我再考虑之前的问题,es6的数组解构赋值是不是直接调用next方法了?查了下资料,发现的确是这样啊,查阅 exporting es6 -- Destructuring, 第一行就是。

额,这个有点坑,我不确定是不是只有yield是这样,只要不加分号,他就认为你这个表达式还没有结束,反正是挺坑的啊,希望自己能把添加分号作为一个习惯。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant