[,,,] 的长度?

x33g5p2x  于2022-02-12 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(273)

[,,,] 的长度为3
javascript一开始就支持数组字面量的尾号逗号,随后在es2015中将对象字面量添加进入,在es2017中将其添加到函数中。

  1. let arr = [1, 2, 3, ]
  2. console.log(arr) //[1,2,3]
  3. console.log(arr.length) //3

如果使用多个尾号逗号,在对数组使用forEach,map等方法时,会进行忽略。
在ES2015中,对象使用尾后逗号也是合法的。

  1. let obj = {
  2. name:"zs",
  3. age:20,
  4. }
  5. console.log(obj) //{name:"zs",age:20}

函数中的尾后逗号
ES2017中支持函数参数的尾号逗号。

  1. function add(a, b, ) {
  2. return a + b
  3. }
  4. console.log(add.length) //2
  5. const sub = (a, b, ) => a + b
  6. console.log(sub.length) //2
  7. 除了在上式中函数,也可以是在对象的方法中进行设置。
  8. let bar = {
  9. foo: function (a, b, ) {
  10. return a + b
  11. }
  12. }
  13. console.log(bar.foo.length) //2
  14. 函数调用也是合法的,并且也是等价的
  15. add(10,20,)
  16. add(10,20)

不合法的尾号逗号
当函数不需要传递参数,但是在其中添加了一个逗号,会报错。
当函数剩余参数后面存在尾号逗号,会报错。
JSON中的尾号逗号
如果在json中存在尾号逗号,会直接报错。

相关文章