Return multiple values in JavaScript?

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

    In JS, we can easily return a tuple with an array or object, but do not forget! => JS is a callback oriented language, and there is a little secret here for "returning multiple values" that nobody has yet mentioned, try this:

    var newCodes = function() {  
        var dCodes = fg.codecsCodes.rs;
        var dCodes2 = fg.codecsCodes2.rs;
        return dCodes, dCodes2;
    };
    

    becomes

    var newCodes = function(fg, cb) {  
        var dCodes = fg.codecsCodes.rs;
        var dCodes2 = fg.codecsCodes2.rs;
        cb(null, dCodes, dCodes2);
    };
    

    :)

    bam! This is simply another way of solving your problem.

    0 讨论(0)
  • 2020-11-22 14:21

    A very common way to return multiple values in javascript is using an object literals, so something like:

    const myFunction = () => {
      const firstName = "Alireza", 
            familyName = "Dezfoolian",
            age = 35;
      return { firstName, familyName, age};
    }
    

    and get the values like this:

    myFunction().firstName; //Alireza
    myFunction().familyName; //Dezfoolian
    myFunction().age; //age
    

    or even a shorter way:

    const {firstName, familyName, age} = myFunction();
    

    and get them individually like:

    firstName; //Alireza
    familyName; //Dezfoolian
    age; //35
    
    0 讨论(0)
提交回复
热议问题