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 02:05

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. Hope it helped you :)

查看更多
若你有天会懂
3楼-- · 2019-01-01 02:07

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

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.

查看更多
墨雨无痕
4楼-- · 2019-01-01 02:08

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

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

Then you can access them like so:

var codes = newCodes();
var dCodes = codes[0];
var dCodes2 = codes[1];

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

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

And to access them:

var codes = newCodes();
var dCodes = codes.dCodes;
var dCodes2 = codes.dCodes2;
查看更多
登录 后发表回答