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

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

当前回答

几天前,我有类似的要求,从我创建的函数中获得多个返回值。

从许多返回值,我需要它只返回特定的值为一个给定的条件,然后其他返回值对应于其他条件。


以下是我如何做到这一点的例子:

功能:

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

从函数返回的对象获取所需的返回值:

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

回答这个问题的关键是分享以良好格式获取Date的方法。希望对你有所帮助:)

其他回答

你可以使用Object

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

    return obj;
}

我知道有两种方法: 1. 返回为数组 2. 返回为对象

下面是我找到的一个例子:

<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>
function a(){
  var d = 2;
  var c = 3;
  var f = 4;
  return {d: d, c: c, f: f};
}

然后使用

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

新版本:

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

从ES6开始,你可以这样做

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

let {dCodes, dCodes2} = newCodes()

返回表达式{dCodes, dCodes2}是属性值的简写,等价于这个{dCodes: dCodes, dCodes2: dCodes2}。

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

除了像其他人推荐的那样返回一个数组或对象,你还可以使用一个收集器函数(类似于在the Little Schemer中找到的那个):

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

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

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

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