简体   繁体   English

函数体中的 JavaScript 逗号分隔值

[英]JavaScript comma seperated values in function body

I recently read some source code that contained a function similar to the one below:我最近阅读了一些包含类似于以下功能的源代码:

function foo(someArray) {
  const arrayPrime = someArray.map(x => x * 2,);
  return arrayPrime;
}

To my surprise, the code above is valid - no syntax errors.令我惊讶的是,上面的代码是有效的 - 没有语法错误。

Playing with this code more, we can add any number of values separated by commas without generating a syntax error:多玩这段代码,我们可以添加任意数量的以逗号分隔的值,而不会产生语法错误:

function foo(someArray) {
  const arrayPrime = someArray.map(x => x * 2, 3, 4, 5, 6);
  return arrayPrime;
}

Invoking both versions of foo with foo([11,2,3]) yields 22,4,6 .使用foo([11,2,3])调用两个版本的foo产生22,4,6

Can someone explain why this is legal?有人可以解释为什么这是合法的吗?

Those are additional arguments to the map() method.这些是map()方法的附加参数。

map() takes 1 optional argument, the value to be passed as the this context to the callback function. map()接受 1 个可选参数,该值作为this上下文传递给回调函数。 Since arrow functions can't have their this value altered, so it's ignored in this case.由于箭头函数不能改变它们的this值,所以在这种情况下它被忽略了。

The remaining arguments are ignored completely.其余参数将被完全忽略。 JavaScript doesn't report errors when a function is called with more arguments than it needs.当一个函数被调用的参数多于它需要的时候,JavaScript 不会报告错误。 (It also doesn't report errors for missing arguments, they're just set to undefined ). (它也不会报告缺少参数的错误,它们只是设置为undefined )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM