简体   繁体   English

什么是相当于Ruby的splat运算符的JavaScript?

[英]What's the JavaScript equivalent of Ruby's splat operator?

In Ruby, you can use the splat ( * ) operator to capture a variable number of arguments to a function, or to send the contents of an array to a function as an argument, like so: 在Ruby中,您可以使用splat( * )运算符捕获函数的可变数量的参数,或者将数组的内容作为参数发送到函数,如下所示:

def example(arg1, *more_args)
  puts "Argument 1: #{arg1.inspect}"
  puts "Other arguments: #{more_args.inspect}"
end

test_args = [1, 2, 3]

example(*test_args)

Output: 输出:

Argument 1: 1
Other arguments: [2, 3]

What's the equivalent of this in JavaScript? JavaScript中的等价物是什么?

In older versions of JavaScript (ECMAScript 5), no exact equivalent to this exists. 在较旧版本的JavaScript(ECMAScript 5)中,并不存在与此完全等效的内容。 In modern browsers which support ECMAscript 6 though, there is something very similar denoted by three periods ( ... ). 在支持ECMAscript 6的现代浏览器中,有一些非常相似的东西由三个句点( ... )表示。

When used in function calls and array declarations this triple-dot syntax is known as the spread operator . 当在函数调用和数组声明中使用时,这种三点语法称为扩展运算符 When used in a function definition, it is called rest parameters . 在函数定义中使用时,它被称为rest参数

Example: 例:

function example(arg1, ...more_args) { // Rest parameters
  console.log("Argument 1: ", arg1)
  console.log("Other arguments: ", more_args)
}

test_args = [1, 2, 3]

example(...test_args) // Spread operator

Output: 输出:

Argument 1:  1
Other arguments:  [2, 3]

The spread operator and rest parameters are available in the latest versions of all major browsers (except Internet Explorer) and the latest Node.js LTS release. 扩展运算符和rest参数可在所有主流浏览器的最新版本(Internet Explorer除外)和最新的Node.js LTS版本中使用。

Full compatibility tables: Spread operator , Rest parameters 完全兼容性表: Spread运算符Rest参数

The first use can be accomplished (messily) using Array.slice(arguments) . 第一次使用可以使用Array.slice(arguments)完成( Array.slice(arguments)

The second can be accomplished by using the .apply() method of your function. 第二个可以通过使用函数的.apply()方法来完成。

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

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