Return multiple values in JavaScript?

前端 未结 20 2010
暖寄归人
暖寄归人 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:16

    Adding the missing important parts to make this question a complete resource, as this comes up in search results.

    Object Destructuring

    In object destructuring, you don't necessarily need to use the same key value as your variable name, you can assign a different variable name by defining it as below:

    const newCodes = () => {  
        let dCodes = fg.codecsCodes.rs;
        let dCodes2 = fg.codecsCodes2.rs;
        return { dCodes, dCodes2 };
    };
    
    //destructuring
    let { dCodes: code1, dCodes2: code2 } = newCodes();
    
    //now it can be accessed by code1 & code2
    console.log(code1, code2);
    

    Array Destructuring

    In array destructuring, you can skip the values you don't need.

    const newCodes = () => {  
        //...
        return [ dCodes, dCodes2, dCodes3 ];
    };
    
    let [ code1, code2 ] = newCodes(); //first two items
    let [ code1, ,code3 ] = newCodes(); //skip middle item, get first & last
    let [ ,, code3 ] = newCodes(); //skip first two items, get last
    let [ code1, ...rest ] = newCodes(); //first item, and others as an array
    

    It's worth noticing that ...rest should always be at the end as it doesn't make any sense to destruct anything after everything else is aggregated to rest.

    I hope this will add some value to this question :)

提交回复
热议问题