I've heard Javascript inserts “;” automatically and that may cause problems [duplicate]

半腔热情 提交于 2019-12-19 05:08:14

问题


I've also heard that Go insert them too, but they followed a different approach

How does Javascript insert semicolons while interpreting?


回答1:


One of the biggest things I've found is, let's say you have a function that returns coordinates (or any object really), similar to this.

function getCoordinates() {
    return
        {
            x: 10,
            y: 10
        };
}

You would expect to get back an object right? WRONG! You get back undefined. The interpreter converts the code into this

function getCoordinates() {
    return;
        {
            x: 10,
            y: 10
        };
}

Since return by itself is a valid statement. You need to be sure to write the return as follows

function getCoordinates() {
    return {
            x: 10,
            y: 10
        };
}



回答2:


Javascript assumes end of statement at any line break where it's possible. For example this:

return
true;

is interpreted as:

return;
true;

turning the return and it's argument into two separate statements, which of course means that the function has no return value (returns undefined).

I wrote a blog entry about that a while back.




回答3:


The example that taught me the pitfalls of this particular feature was this one in the "Strangest language feature?" question. (Which is why I was for reopening that question, by the way - it is a valuable learning resource.)

Good reference material can be found here: What are the rules for Javascript's automatic semicolon insertion?



来源:https://stackoverflow.com/questions/4054204/ive-heard-javascript-inserts-automatically-and-that-may-cause-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!