博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何从JavaScript中的函数返回多个值
阅读量:2505 次
发布时间:2019-05-11

本文共 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.

现在,我们有了包含这些值的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的顺序不再重要,因为它们是命名参数。

翻译自:

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

你可能感兴趣的文章
WordPress资源站点推荐
查看>>
Python性能鸡汤
查看>>
android Manifest.xml选项
查看>>
Cookie/Session机制具体解释
查看>>
ATMEGA16 IOport相关汇总
查看>>
有意思的cmd命令
查看>>
js正則表達式语法
查看>>
JVM-垃圾回收
查看>>
ubuntu-14.04.1-desktop上安装配置JDK1.8的环境变量
查看>>
VS2013 添加已有文件夹
查看>>
摄影扫盲
查看>>
POJ 2388 - Who's in the Middle
查看>>
python 计时程序运行时间
查看>>
【最小生成树+贪心】BZOJ1821: [JSOI2010]Group 部落划分 Group
查看>>
ios-自动布局指南:入门
查看>>
【Shell脚本学习4】几种常见的Shell
查看>>
DataStructure part1 基础概念
查看>>
201521123007《Java程序设计》第11周学习总结
查看>>
BitLocker 加密工具挂起和恢复命令行(windows7)
查看>>
VMware下centos7安装VMware Tools
查看>>