简体   繁体   English

在 JavaScript 中返回多个值?

[英]Return multiple values in JavaScript?

I am trying to return two values in JavaScript .我试图在JavaScript中返回两个值。 Is this possible?这可能吗?

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

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 table for 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。

You can do this from ECMAScript 6 onwards using arrays and "destructuring assignments" .从 ECMAScript 6 开始,您可以使用数组和“解构赋值”来执行此操作。 Note that these are not available in older Javascript versions (meaning — neither with ECMAScript 3rd nor 5th editions).请注意,这些在较旧的 Javascript 版本中不可用(即 ECMAScript 第 3 版和第 5 版均不可用)。

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 shorthand to 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, ... .顺便说一句,不要被 ECMAScript 允许您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 . return 语句中的表达式 - 1, 2, 3 - 只不过是按顺序应用于数字文字( 123 )的逗号运算符,最终计算为其最后一个表达式的值 - 3 That's why return 1, 2, 3 is functionally identical to nothing more but return 3 .这就是为什么return 1, 2, 3在功能上与return 3相同。

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

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);

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 shorthand and is equivalent to this {dCodes: dCodes, dCodes2: dCodes2} .返回表达式{dCodes, dCodes2}属性值简写,等价于{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()

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 中试用了!

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 为旧版浏览器填充,但幸运的是现在可以在最新版本的 Chrome 和 Firefox 中原生使用。

But as making a new object, memory allocation (and eventual gc load) are involved here, don't expect much performance from it.但是作为创建一个新对象,这里涉及内存分配(和最终的 gc 加载),不要期望它有太多的性能。 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. JavaScript 无论如何都不是开发高度优化事物的最佳语言,但如果需要,您可以考虑将结果放在周围对象或此类技术上,这些技术通常是 JavaScript、Java 和其他语言之间常见的性能技巧。

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

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.我做了一个jsperf测试,看看这三种方法中哪一种更快。 Array is fastest and collector is slowest.数组最快,收集器最慢。

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

In JS, we can easily return a tuple with an array or object, but do not forget!在 JS 中,我们可以轻松地返回带有数组或对象的元组,但不要忘记! => JS is a callback oriented language, and there is a little secret here for "returning multiple values" that nobody has yet mentioned, try this: => 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.这只是解决您的问题的另一种方法。

A very common way to return multiple values in javascript is using an object literals , so something like:在 javascript 中返回多个值的一种非常常见的方法是使用对象文字,例如:

const myFunction = () => {
  const firstName = "Alireza", 
        familyName = "Dezfoolian",
        age = 35;
  return { firstName, familyName, age};
}

and get the values like this:并得到这样的值:

myFunction().firstName; //Alireza
myFunction().familyName; //Dezfoolian
myFunction().age; //age

or even a shorter way:甚至更短的方式:

const {firstName, familyName, age} = myFunction();

and get them individually like:并单独获取它们,例如:

firstName; //Alireza
familyName; //Dezfoolian
age; //35

You can also do:你也可以这样做:

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

const {d,c,f} = a()

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 ...rest should 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 :)我希望这会给这个问题增加一些价值:)

You can use "Object"您可以使用“对象”

function newCodes(){
    var obj= new Object();
    obj.dCodes = fg.codecsCodes.rs;
    obj.dCodes2 = fg.codecsCodes2.rs;

    return obj;
}

All's correct.一切都是正确的。 return logically processes from left to right and returns the last value. return从左到右进行逻辑处理并返回最后一个值。

function foo(){
    return 1,2,3;
}

>> foo()
>> 3

I would suggest to use the latest destructuring assignment (But make sure it's supported in your environment )我建议使用最新的解构分配(但请确保它在您的环境中受支持

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

I know of two ways to do this: 1. Return as Array 2. Return as Object我知道有两种方法可以做到这一点: 1. 作为数组返回 2. 作为对象返回

Here's an example I found:这是我发现的一个例子:

<script>
// Defining function
function divideNumbers(dividend, divisor){
    var quotient = dividend / divisor;
    var arr = [dividend, divisor, quotient];
    return arr;
}

// Store returned value in a variable
var all = divideNumbers(10, 2);

// Displaying individual values
alert(all[0]); // 0utputs: 10
alert(all[1]); // 0utputs: 2
alert(all[2]); // 0utputs: 5
</script>



<script>
// Defining function
function divideNumbers(dividend, divisor){
    var quotient = dividend / divisor;
    var obj = {
        dividend: dividend,
        divisor: divisor,
        quotient: quotient
    };
    return obj;
}

// Store returned value in a variable
var all = divideNumbers(10, 2);

// Displaying individual values
alert(all.dividend); // 0utputs: 10
alert(all.divisor); // 0utputs: 2
alert(all.quotient); // 0utputs: 5
</script>

Few Days ago i had the similar requirement of getting multiple return values from a function that i created.几天前,我有类似的要求,即从我创建的函数中获取多个返回值。

From many return values , i needed it to return only specific value for a given condition and then other return value corresponding to other condition.从许多返回值中,我需要它只返回给定条件的特定值,然后返回与其他条件相对应的其他返回值。


Here is the Example of how i did that :这是我如何做到的示例:

Function:功能:

function myTodayDate(){
    var today = new Date();
    var day = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    var month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
    var myTodayObj = 
    {
        myDate : today.getDate(),
        myDay : day[today.getDay()],
        myMonth : month[today.getMonth()],
        year : today.getFullYear()
    }
    return myTodayObj;
}

Getting Required return value from object returned by function :从函数返回的对象中获取所需的返回值:

var todayDate = myTodayDate().myDate;
var todayDay = myTodayDate().myDay;
var todayMonth = myTodayDate().myMonth;
var todayYear = myTodayDate().year;

The whole point of answering this question is to share this approach of getting Date in good format.回答这个问题的重点是分享这种以良好格式获取 Date 的方法。 Hope it helped you :)希望它对你有帮助:)

I am nothing adding new here but another alternate way.我在这里没有添加新内容,而是另一种替代方式。

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

Well we can not exactly do what your trying.好吧,我们不能完全按照您的尝试去做。 But something likely to below can be done.但是可以做一些可能低于的事情。

function multiReturnValues(){
    return {x:10,y:20};
}

Then when calling the method然后在调用方法的时候

const {x,y} = multiReturnValues();

console.log(x) ---> 10
console.log(y) ---> 20
    <script>
    function getValue()
    {
    var obj={
    name:"test",
    sub:"xyz",
    dept:"Developing"
    };
    return obj;
    }

    var getval=getValue();
    console.log("Name Is: " + getval.name);   //will return Name Is: test
    </script>

click here to see the video 点击这里观看视频

It is possible to return a string with many values and variables using the template literals `${}`可以使用模板文字`${}`返回一个包含许多值和变量的字符串

like:喜欢:

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

It's short and simple.它简短而简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM