Return multiple values in JavaScript?
I am trying to return two values in JavaScript. Is that possible?
我在嘗試在 JS上 return多個值,有可能做到嗎?
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
No, but you could return an array containing your values:
不行,但你可以return一個陣列內帶你所有的值:
function getValues() {
return [getFirstValue(), getSecondValue()];
}
Then you can access them like so:
然後可以這樣取用:
var values = getValues();
var first = values[0];
var second = values[1];
With the latest ECMAScript 6 syntax*, you can also destructure the return value more intuitively:
const [first, second] = getValues();
If you want to put "labels" on each of the returned values (easier to maintain), you can return an object:
如果你想放"labels"在每個return的值(比較易於維護)你可以return一個物件:
function getValues() {
return {
first: getFirstValue(),
second: getSecondValue(),
};
}
And to access them:
然後取用它們
var values = getValues();
var first = values.first;
var second = values.second;
Or with ES6 syntax:
或者ES6的語法
const {first, second} = getValues();