如何从JavaScript中的函数返回多个值

When we call a function in JavaScript, we can only return one value using the return statement:

当我们使用JavaScript调用函数时,只能使用return语句返回一个值:

const getAge = () => {
  return 37
}

const getName = () => {
  return 'Flavio'
}

How can we return multiple values from a function?

我们如何从一个函数返回多个值?

One easy trick is to return an array

一个简单的技巧是返回一个数组

const getDetails = () => {
  return [ 37 , 'Flavio' ]
}

This is fine, and we can get the values in this way thanks to array destructuring:

很好,由于数组的分解,我们可以通过这种方式获取值:

const [ age , name ] = getDetails ()

Now we have the age and name variables that contain those values.

现在,我们有了包含这些值的agename变量。

Note that the order we define those in const [age, name] = getDetails() matters.

请注意,我们在const [age, name] = getDetails()定义的顺序很重要。

We can also return an object and use object destructuring:

我们还可以返回一个对象并使用对象分解:

const getDetails = () => {
  return { 
    age : 37 , 
    name : 'Flavio'
  }
}

const { age , name } = getDetails ()

In this case, the order of age and name in const { age, name } = getDetails() does not matter any more, because those are named parameters.

在这种情况下, const { age, name } = getDetails()中的agename的顺序不再重要,因为它们是命名参数。

翻译自: https://flaviocopes.com/javascript-return-multiple-values/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值