我试图在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;
};
当前回答
我并不是在这里添加新内容,而是另一种替代方法。
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
let [...val] = [dCodes,dCodes2];
return [...val];
};
其他回答
你还可以:
function a(){
var d=2;
var c=3;
var f=4;
return {d:d,c:c,f:f}
}
const {d,c,f} = a()
我知道有两种方法: 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}
}
我建议使用最新的解构赋值(但要确保它在您的环境中得到支持)
var newCodes = function () {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return {firstCodes: dCodes, secondCodes: dCodes2};
};
var {firstCodes, secondCodes} = newCodes()
我们做不到你想做的事。但可能低于这个水平的事情是可以做到的。
function multiReturnValues(){
return {x:10,y:20};
}
然后在调用方法时
const {x,y} = multiReturnValues();
console.log(x) ---> 10
console.log(y) ---> 20