iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 27
0
Modern Web

從Stack Overflow學前端系列 第 27

從StackOverflow上學CODING(27) JS return多個值

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

上一篇
從StackOverflow上學CODING(26) setTimeout或 setInterval?
下一篇
從StackOverflow上學CODING(28) 判斷兩個陣列中的不同點
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言