Return multiple values in JavaScript?

前端 未结 20 2306
暖寄归人
暖寄归人 2020-11-22 13:17

I am trying to return two values in JavaScript. Is this possible?

var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    va         


        
20条回答
  •  面向向阳花
    2020-11-22 14:03

    No, but you could return an array containing your values:

    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:

    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:

    const {first, second} = getValues();
    

    * See this table for browser compatibility. Basically, all modern browsers aside from IE support this syntax, but you can compile ES6 code down to IE-compatible JavaScript at build time with tools like Babel.

提交回复
热议问题