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

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

当前回答

我并不是在这里添加新内容,而是另一种替代方法。

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

其他回答

你可以使用Object

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

    return obj;
}

我并不是在这里添加新内容,而是另一种替代方法。

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

另一个值得一提的是新引入的(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);

这个语法可以用babel或其他旧浏览器的js polyfiller填充,但幸运的是,现在本机适用于最新版本的Chrome和Firefox。

但是在创建一个新对象时,这里涉及到内存分配(以及最终的gc负载),因此不要期望从它那里获得太多性能。JavaScript不是开发高度优化的东西的最佳语言,但如果需要,你可以考虑将结果放在周围的对象上,或者是JavaScript、Java和其他语言之间常见的性能技巧。

我知道有两种方法: 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>

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

你已经可以在Firefox中尝试了!