Return multiple values in JavaScript?

2019-01-01 01:27发布

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

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

标签: javascript
15条回答
看风景的人
2楼-- · 2019-01-01 01:41

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

in ES6 you can use this code

function a(){
      var d=2;
      var c=3;
      var f=4;
      return {d,c,f}
}
查看更多
深知你不懂我心
3楼-- · 2019-01-01 01:44

You can use "Object"

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

    return obj;
}
查看更多
何处买醉
4楼-- · 2019-01-01 01:46

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);
查看更多
墨雨无痕
5楼-- · 2019-01-01 01:47

Since ES6 you can do this

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}.

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

查看更多
情到深处是孤独
6楼-- · 2019-01-01 01:49

All's correct. return logically processes from left to right and returns the last value.

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

>> foo()
>> 3
查看更多
何处买醉
7楼-- · 2019-01-01 01:50

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.

//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!

查看更多
登录 后发表回答