在 ES11 中,JavaScript 引入了一个新特性——Numeric Separators。这个新特性使得我们可以更简单、更易读地表示数字。在本文中,我们将详细介绍 Numeric Separators,包括其语法、用法、示例以及注意事项。
什么是 Numeric Separators?
Numeric Separators 是 ES11 新引入的一个特性,它允许在数字中使用下划线 _
来分隔数字的不同部分,使得数字更易读。在之前的版本中,我们需要手动计算并且编写无用的 0 补位来区分不同的数字位,例如:
const oneMillion = 1000000; const twoMillion = 2000000; const oneBillion = 1000000000; const twoBillion = 2000000000;
在使用 Numeric Separators 之后,我们可以使用下划线 _
来将数字分隔成更易读的形式,例如:
const oneMillion = 1_000_000; const twoMillion = 2_000_000; const oneBillion = 1_000_000_000; const twoBillion = 2_000_000_000;
可以看到,使用 Numeric Separators 可以使得数字更加易读,同时也能够减少编写不必要的 0 补位的时间。
Numeric Separators 的语法
Numeric Separators 的语法非常简单,只需在两个数字之间加上下划线 _
即可。下面是使用 Numeric Separators 的语法示例:
const a = 1_000_000; // 百万 const b = 0.000_001; // 百万分之一 const c = 0x1_0000_0000; // 十六进制 const d = 0b1010_1010_1010_1010; // 二进制 const e = 0o775_000_000; // 八进制
使用 Numeric Separators 只需要将数字中的 _
去除即可,与普通的数字表示法没有任何区别。
Numeric Separators 的用途
Numeric Separators 的主要用途是提高数字的可读性,并且减少写代码的时间。通过使用 Numeric Separators,我们可以更加方便地区分不同的数字位。例如,以下是两个没有使用 Numeric Separators 的数字:
const number1 = 1000000000; const number2 = 10000000000;
如果没有使用 Numeric Separators,我们很难一眼看出这两个数字的差别。但是使用 Numeric Separators,我们可以轻松地看出这两个数字的差别:
const number1 = 1_000_000_000; const number2 = 10_000_000_000;
在编写代码的时候,Numeric Separators 也能够大大减少编写 0 补位的时间,从而提高开发者的效率。
Numeric Separators 的示例
下面是一些使用 Numeric Separators 的示例,以及它们如何增加了数字的可读性:
-- -------------------- ---- ------- ----- ------ - ----------- -- --- ----- ------ - -------------- -- ------- ----- ------- - ---- -- -- ----- ------- - ----- -- ------ ----- --------- - ---------- -- -- ----- --------- - ------------ -- ------ ----- ----- - ------------------------------------- -- --- ----- ----- - --------------------------------------------- -- ------- ----- ---- - ----------- -- ---- ----- ---- - ------------ -- -------- ----- ------ - ----------- -- --- ----- ------ - ------------- -- -------展开代码
注意事项
不允许在数字的开头和结尾使用下划线
Numeric Separators 要求我们只能在数字的中间使用下划线,不允许在数字的开头和结尾使用下划线。例如,以下的代码是错误的:
const number1 = _100_000_; const number2 = 100_000_; const number3 = 100_000__
不允许在小数点前面使用下划线
Numeric Separators 不允许在小数点前面使用下划线,否则会抛出语法错误。例如,以下的代码是错误的:
const number1 = 1._000_000; const number2 = 1.__000_000; const number3 = 1._000_000_;
不推荐在数字中间只使用单个下划线
Numeric Separators 虽然允许在数字中间使用下划线,但是单个下划线的可读性并不好。因此,不推荐在数字中间只使用单个下划线。例如,以下的代码并不推荐使用:
const number1 = 1_000_00_; const number2 = 1_000000_; const number3 = 1_00_00_0_;
结论
Numeric Separators 是 ES11 中引入的一个新特性,它允许我们在数字中间使用下划线 _
分隔数字的不同部分,使得数字更加易读。在编写代码的时候,Numeric Separators 能够大大减少编写 0 补位的时间,提高开发者的效率。同时,我们需要注意在数字的开头和结尾以及小数点前面不允许使用下划线。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/673571cc0bc820c5824e7a2a