博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在JavaScript函数中接受无限的参数
阅读量:2508 次
发布时间:2019-05-11

本文共 1770 字,大约阅读时间需要 5 分钟。

Let’s say we have a function called join() whose job is to join all the strings we pass to it.

假设我们有一个名为join()的函数,其作用是将传递给它的所有字符串连接起来。

For example we write a prototype that accepts 2 strings:

例如,我们编写了一个接受2个字符串的原型:

const join = (string1, string2) => {  return string1 + string2}

and when we call it, we get a string that is the concatenation the 2 arguments we pass:

当我们调用它时,我们得到一个字符串,该字符串是我们传递的两个参数的串联:

join('hi', ' flavio') // 'hi flavio'

One simple way is to append additional parameters that default to an empty string, like this:

一种简单的方法是将默认附加到空字符串的其他参数附加起来,如下所示:

const join = (string1, string2, string3 = '') => {  return string1 + string2 + string3}

but this approach does not scale well, because we’d need to add a large number of parameters and our code would look pretty bad.

但是这种方法无法很好地扩展,因为我们需要添加大量参数,并且我们的代码看起来很糟糕。

Instead, we can use this syntax, with the spread operator (...) followed by the name of the parameter we want to use. Inside the function, the parameter is an array, so we can simply call its .join() method to concatenate the strings it contains, passing an empty string as argument (otherwise it defaults to concatenate strings adding a comma between them):

取而代之的是,我们可以使用这种语法,在扩展运算符( ... )后面加上我们要使用的参数名称。 在函数内部,参数是一个数组,因此我们可以简单地调用其.join()方法来连接包含的字符串,并传递一个空字符串作为参数(否则,默认情况下是将字符串连接起来,并在它们之间添加逗号):

const join = (...strings) => {  return strings.join('')}

In our case we can also simplify this using the implicit return syntax available in arrow functions:

在我们的案例中,我们还可以使用箭头函数中可用的隐式返回语法来简化此操作:

const join = (...strings) => strings.join('')

and we can call this in the same way we did before:

我们可以像以前一样调用它:

join('hi', ' flavio') // 'hi flavio'join('hi', ' flavio', ' it', ' is', ' a', ' beautiful day!') // ''hi flavio it is a beautiful day!'

翻译自:

转载地址:http://ltmgb.baihongyu.com/

你可能感兴趣的文章
展望2018
查看>>
python几大排序算法
查看>>
hdu 4619 二分图最大匹配 ——最大独立集
查看>>
数据结构系列之2-3-4树的插入、查找、删除和遍历完整版源代码实现与分析(dart语言实现)...
查看>>
VM CentOS 问题汇总
查看>>
这段时间的小结
查看>>
ANDROID_MARS学习笔记_S01原始版_021_MP3PLAYER001_下载mp3文件
查看>>
8个基本的引导工具的网页设计师
查看>>
第二周周六DailyReporting——PM(李忠)
查看>>
Beta阶段DAY3
查看>>
windows server 2008 R2 NPS(网络连接策略服务)设置radius,实现telent登陆交换机路由器权限分配...
查看>>
Java中静态变量和动态变量
查看>>
vim的visual可视模式(转载)
查看>>
ASP.NET MVC 学习笔记-6.异步控制器
查看>>
java_赋值与初始化
查看>>
函数如何调用?
查看>>
3.2.2 线性表的顺序存储实现
查看>>
TP框架 ---空控制器和空操作
查看>>
poj 1845 Sumdiv (等比求和+逆元)
查看>>
iView 的后台管理系统简易模板 iview-admin-simple
查看>>