我试图在JavaScript中返回两个值。这可能吗?
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
我试图在JavaScript中返回两个值。这可能吗?
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
当前回答
我们做不到你想做的事。但可能低于这个水平的事情是可以做到的。
function multiReturnValues(){
return {x:10,y:20};
}
然后在调用方法时
const {x,y} = multiReturnValues();
console.log(x) ---> 10
console.log(y) ---> 20
其他回答
我知道有两种方法: 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>
除了像其他人推荐的那样返回一个数组或对象,你还可以使用一个收集器函数(类似于在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
我建议使用最新的解构赋值(但要确保它在您的环境中得到支持)
var newCodes = function () {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return {firstCodes: dCodes, secondCodes: dCodes2};
};
var {firstCodes, secondCodes} = newCodes()
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中尝试了!
不能,但是你可以返回一个包含你的值的数组:
function getValues() {
return [getFirstValue(), getSecondValue()]
}
然后你可以像这样访问它们:
const [first, second] = getValues()
这被称为解构赋值,每个主要的JS环境都支持它。它等价于如下:
const values = getValues()
const first = values[0]
const second = values[1]
如果你想给每个值赋一个名字,你也可以返回一个对象:
function getValues() {
return {
first: getFirstValue(),
second: getSecondValue(),
}
}
要访问它们:
const {first, second} = getValues()
也就是:
const values = getValues()
const first = values.first
const second = values.second
强烈建议返回一个对象而不是数组,除非值作为简单的元组有意义,例如,坐标对[x, y]。使用数组时,很容易忘记哪个值是哪个值,以后更难添加更多的值,而且使用TypeScript或JSDoc正确输入也稍微困难一些。