本文共 1158 字,大约阅读时间需要 3 分钟。
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.
现在,我们有了包含这些值的age
和name
变量。
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()
中的age
和name
的顺序不再重要,因为它们是命名参数。
翻译自:
转载地址:http://otmgb.baihongyu.com/