在 JavaScript 中返回多个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2917175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:29:05  来源:igfitidea点击:

Return multiple values in JavaScript?

javascriptreturnmultiple-variable-return

提问by Asim Zaidi

I am trying to return two values in JavaScript. Is this possible?

我试图在JavaScript 中返回两个值。这可能吗?

var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};

回答by Sasha Chedygov

No, but you could return an array containing your values:

不,但您可以返回一个包含您的值的数组:

function getValues() {
    return [getFirstValue(), getSecondValue()];
}

Then you can access them like so:

然后你可以像这样访问它们:

var values = getValues();
var first = values[0];
var second = values[1];

With the latest ECMAScript 6 syntax*, you can also destructure the return value more intuitively:

使用最新的ECMAScript 6 语法*,还可以更直观地解构返回值:

const [first, second] = getValues();

If you want to put "labels" on each of the returned values (easier to maintain), you can return an object:

如果您想在每个返回值上放置“标签”(更易于维护),您可以返回一个对象:

function getValues() {
    return {
        first: getFirstValue(),
        second: getSecondValue(),
    };
}

And to access them:

并访问它们:

var values = getValues();
var first = values.first;
var second = values.second;

Or with ES6 syntax:

或者使用 ES6 语法:

const {first, second} = getValues();

* See this tablefor browser compatibility. Basically, all modern browsers aside from IE support this syntax, but you can compile ES6 code down to IE-compatible JavaScript at build time with tools like Babel.

* 有关浏览器兼容性,请参阅此表。基本上,除 IE 之外的所有现代浏览器都支持这种语法,但是您可以在构建时使用Babel 等工具将 ES6 代码编译为与 IE 兼容的 JavaScript 。

回答by kangax

You can do this from Javascript 1.7 onwards using "destructuring assignments". Note that these are not available in older Javascript versions (meaning — neither with ECMAScript 3rd nor 5th editions).

从 Javascript 1.7 开始,您可以使用"destructuring assignments"执行此操作。请注意,这些在较旧的 Javascript 版本中不可用(意思是 - ECMAScript 3rd 和 5th 版本都没有)。

It allows you to assign to 1+ variables simultaneously:

它允许您同时分配 1+ 个变量:

var [x, y] = [1, 2];
x; // 1
y; // 2

// or

[x, y] = (function(){ return [3, 4]; })();
x; // 3
y; // 4

You can also use object destructuring combined with property value shorthandto name the return values in an object and pick out the ones you want:

您还可以使用对象解构结合属性值速记来命名对象中的返回值并挑选出您想要的:

let {baz, foo} = (function(){ return {foo: 3, bar: 500, baz: 40} })();
baz; // 40
foo; // 3

And by the way, don't be fooled by the fact that ECMAScript allows you to return 1, 2, .... What really happens there is not what might seem. An expression in return statement — 1, 2, 3— is nothing but a comma operator applied to numeric literals (1, 2, and 3) sequentially, which eventually evaluates to the value of its last expression — 3. That's why return 1, 2, 3is functionally identical to nothing more but return 3.

顺便说一句,不要被 ECMAScript 允许您return 1, 2, .... 那里真正发生的事情并不像看起来的那样。return 语句中的表达式 — 1, 2, 3— 只不过是一个逗号运算符,按顺序应用于数字文字 ( 1, 2, 和3),最终计算为其最后一个表达式 — 的值3。这就是为什么return 1, 2, 3在功能上与return 3.

return 1, 2, 3;
// becomes
return 2, 3;
// becomes
return 3;

回答by Sean Kinsey

Just return an object literal

只返回一个对象字面量

function newCodes(){
    var dCodes = fg.codecsCodes.rs; // Linked ICDs  
    var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs       
    return {
        dCodes: dCodes, 
        dCodes2: dCodes2
    };  
}


var result = newCodes();
alert(result.dCodes);
alert(result.dCodes2);

回答by Peracek

Since ES6 you can do this

从 ES6 开始,你可以这样做

let newCodes = function() {  
    const dCodes = fg.codecsCodes.rs
    const dCodes2 = fg.codecsCodes2.rs
    return {dCodes, dCodes2}
};

let {dCodes, dCodes2} = newCodes()

Return expression {dCodes, dCodes2}is property value shorthandand is equivalent to this {dCodes: dCodes, dCodes2: dCodes2}.

返回表达式{dCodes, dCodes2}属性值的简写,相当于 this {dCodes: dCodes, dCodes2: dCodes2}

This assignment on last line is called object destructing assignment. It extracts property value of an object and assigns it to variable of same name. If you'd like to assign return values to variables of different name you could do it like this let {dCodes: x, dCodes2: y} = newCodes()

最后一行的赋值称为对象破坏赋值。它提取对象的属性值并将其分配给同名变量。如果您想将返回值分配给不同名称的变量,您可以这样做let {dCodes: x, dCodes2: y} = newCodes()

回答by user3015682

Ecmascript 6 includes "destructuring assignments" (as kangax mentioned) so in all browsers (not just Firefox) you'll be able to capture an array of values without having to make a named array or object for the sole purpose of capturing them.

Ecmascript 6 包括“解构赋值”(如 kangax 提到的),因此在所有浏览器(不仅仅是 Firefox)中,您将能够捕获一组值,而不必为了捕获它们而创建命名数组或对象。

//so to capture from this function
function myfunction()
{
 var n=0;var s=1;var w=2;var e=3;
 return [n,s,w,e];
}

//instead of having to make a named array or object like this
var IexistJusttoCapture = new Array();
IexistJusttoCapture = myfunction();
north=IexistJusttoCapture[0];
south=IexistJusttoCapture[1];
west=IexistJusttoCapture[2];
east=IexistJusttoCapture[3];

//you'll be able to just do this
[north, south, west, east] = myfunction(); 

You can try it out in Firefox already!

您已经可以在 Firefox 中试用了!

回答by Ebrahim Byagowi

Another worth to mention newly introduced (ES6) syntax is use of object creation shorthand in addition to destructing assignment.

另一个值得一提的新引入的 (ES6) 语法是除析构赋值之外还使用对象创建速记。

function fun1() {
  var x = 'a';
  var y = 'b';
  return { x, y, z: 'c' };
  // literally means { x: x, y: y, z: 'c' };
}

var { z, x, y } = fun1(); // order or full presence is not really important
// literally means var r = fun1(), x = r.x, y = r.y, z = r.z;
console.log(x, y, z);

This syntax can be polyfilled with babel or other js polyfiller for older browsers but fortunately now works natively with the recent versions of Chrome and Firefox.

对于旧浏览器,可以使用 babel 或其他 js polyfiller 对这种语法进行 polyfill,但幸运的是,现在可以与最新版本的 Chrome 和 Firefox 本机一起使用。

But as making a new object, memory allocation (and eventual gc load) are involved here, don't expect much performance from it. JavaScript is not best language for developing highly optimal things anyways but if that is needed, you can consider putting your result on surrounding object or such techniques which are usually common performance tricks between JavaScript, Java and other languages.

但是当创建一个新对象时,这里涉及内存分配(和最终的 gc 负载),不要期望它有太多的性能。JavaScript 无论如何都不是开发高度优化事物的最佳语言,但如果需要,您可以考虑将结果放在周围的对象或此类技术上,这些技术通常是 JavaScript、Java 和其他语言之间常见的性能技巧。

回答by Behnam Mohammadi

Best way for this is

最好的方法是

function a(){
     var d=2;
     var c=3;
     var f=4;
     return {d:d,c:c,f:f}
}

Then use

然后使用

a().f

return 4

返回 4

in ES6 you can use this code

在 ES6 中,您可以使用此代码

function a(){
      var d=2;
      var c=3;
      var f=4;
      return {d,c,f}
}

回答by Zelenova

Other than returning an array or an object as others have recommended, you can also use a collector function (similar to the one found in The Little Schemer):

除了像其他人推荐的那样返回数组或对象之外,您还可以使用收集器函数(类似于The Little Schemer中的那个):

function a(collector){
  collector(12,13);
}

var x,y;
a(function(a,b){
  x=a;
  y=b;
});

I made a jsperf test to see which one of the three methods is faster. Array is fastest and collector is slowest.

我做了一个jsperf测试,看看这三种方法中哪一种更快。数组最快,收集器最慢。

http://jsperf.com/returning-multiple-values-2

http://jsperf.com/returning-multiple-values-2

回答by Alexander Mills

In JS, we can easily return a tuple with an array or object, but do not forget! => JS is a callbackoriented language, and there is a little secret here for "returning multiple values" that nobody has yet mentioned, try this:

在 JS 中,我们可以轻松地返回带有数组或对象的元组,但不要忘记!=> JS 是一种callback面向语言,这里有一个关于“返回多个值”的小秘密,没有人提到过,试试这个:

var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};

becomes

变成

var newCodes = function(fg, cb) {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    cb(null, dCodes, dCodes2);
};

:)

:)

bam! This is simply another way of solving your problem.

砰!这只是解决问题的另一种方法。

回答by Nimeshka Srimal

Adding the missing important parts to make this question a complete resource, as this comes up in search results.

添加缺失的重要部分,使这个问题成为一个完整的资源,因为它出现在搜索结果中。

Object Destructuring

对象解构

In object destructuring, you don't necessarily need to use the same key value as your variable name, you can assign a different variable name by defining it as below:

在对象解构中,您不一定需要使用与变量名相同的键值,您可以通过如下定义来分配不同的变量名:

const newCodes = () => {  
    let dCodes = fg.codecsCodes.rs;
    let dCodes2 = fg.codecsCodes2.rs;
    return { dCodes, dCodes2 };
};

//destructuring
let { dCodes: code1, dCodes2: code2 } = newCodes();

//now it can be accessed by code1 & code2
console.log(code1, code2);

Array Destructuring

数组解构

In array destructuring, you can skip the values you don't need.

在数组解构中,您可以跳过不需要的值。

const newCodes = () => {  
    //...
    return [ dCodes, dCodes2, dCodes3 ];
};

let [ code1, code2 ] = newCodes(); //first two items
let [ code1, ,code3 ] = newCodes(); //skip middle item, get first & last
let [ ,, code3 ] = newCodes(); //skip first two items, get last
let [ code1, ...rest ] = newCodes(); //first item, and others as an array

It's worth noticing that ...restshould always be at the end as it doesn't make any sense to destruct anything after everything else is aggregated to rest.

值得注意的是,...rest应该始终在最后,因为在其他所有内容聚合到rest.

I hope this will add some value to this question :)

我希望这会给这个问题增加一些价值:)