本文共 3155 字,大约阅读时间需要 10 分钟。
javascript 分号
I am in "Effective JavaScript" training at by Douglas Crockford and cannot express what an enlightening experience it has been! I realized today why using explicit semi-colons is so important in JS. Will share my insights soon.
— Shruti Kapoor (@shrutikapoor08)我正在接受Douglas Crockford在进行的“有效JavaScript”培训,并且无法表达出这种启发性的体验! 今天我意识到为什么在JS中使用显式分号如此重要。 即将分享我的见解。
-Shruti Kapoor(@ shrutikapoor08)
I took Effective JavaScript training by a few months ago. One thing that stuck with me since then is the importance of using explicit semicolons in JavaScript. For a while, I have been lazily avoiding writing the ;
and assuming the parser will do my job correctly for me. In this post, I want to present some examples that changed my mindset.
几个月前,我接受了进行的有效JavaScript培训。 从那时起,我一直困扰着我的一件事就是在JavaScript中使用显式分号的重要性。 一段时间以来,我一直在懒惰地避免编写;
并假设解析器将为我正确完成我的工作。 在这篇文章中,我想提出一些改变心态的例子。
What do you expect the output of this to be?
您期望它的输出是什么?
const test = () => { return { ok : true }}console.log(test())
You would expect the output of this to be an object
with a property ok
set to true
. But instead, the output is undefined
. This is so because since the curly brace starts on a new line, automatic semicolon completion changes the above code to this:
您可能希望它的输出是一个object
,其属性ok
设置为true
。 但是,输出是undefined
。 之所以这样,是因为因为花括号在新行开始,所以自动分号完成将上面的代码更改为:
const test = () => { return; { ok : true }}
Fix: Use curly braces on the right of return and explicit semicolons:
修复 :在return和显式分号右边使用花括号:
const test = () => { return { ok : true }};
const a = 1const b = 2(a+b).toString()
What do you think happens in the above code? We get an error Uncaught ReferenceError: b is not defined.
This is because the parenthesis on the third line is interpreted as a function argument. This code is converted to this:
您认为上述代码中发生了什么? 我们收到错误信息Uncaught ReferenceError: b is not defined.
这是因为第三行上的括号被解释为函数参数。 这段代码被转换为:
const a = 1;const b = 2(a+b).toString();
In the circumstance that an assignment statement must begin with a left parenthesis, it is a good idea for the programmer to provide an explicit semicolon at the end of the preceding statement rather than to rely on automatic semicolon insertion.
在赋值语句必须以左括号开头的情况下,对于程序员来说,在前一条语句的末尾提供显式分号而不是依靠自动分号插入是一个好主意。
In the circumstance that an assignment statement must begin with a left parenthesis, it is a good idea for the programmer to provide an explicit semicolon at the end of the preceding statement rather than to rely on automatic semicolon insertion.
在赋值语句必须以左括号开头的情况下,对于程序员来说,在前一条语句的末尾提供显式分号而不是依靠自动分号插入是一个好主意。
I have learned to be careful when using automatic semi-colon insertion.
我学会了使用自动分号插入时要小心。
"I always tell women: when you get to the top, get back in the elevator and bring a woman up with you" - Eunice Kennedy Shriver. Words of wisdom.
— Shruti Kapoor (@shrutikapoor08)“我总是告诉女人:当你到达山顶时,回到电梯里,然后把一个女人带到你身边。”-Eunice Kennedy Shriver。 至理名言。
-Shruti Kapoor(@ shrutikapoor08)
翻译自:
javascript 分号
转载地址:http://jfwzd.baihongyu.com/