Return multiple values in JavaScript?

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

    Another worth to mention newly introduced (ES6) syntax is use of object creation shorthand in addition to destructing assignment.

    function fun1() {
      var x = 'a';
      var y = 'b';
      return { x, y, z: 'c' };
      // literally means { x: x, y: y, z: 'c' };
    }
    
    var { z, x, y } = fun1(); // order or full presence is not really important
    // literally means var r = fun1(), x = r.x, y = r.y, z = r.z;
    console.log(x, y, z);
    

    This syntax can be polyfilled with babel or other js polyfiller for older browsers but fortunately now works natively with the recent versions of Chrome and Firefox.

    But as making a new object, memory allocation (and eventual gc load) are involved here, don't expect much performance from it. JavaScript is not best language for developing highly optimal things anyways but if that is needed, you can consider putting your result on surrounding object or such techniques which are usually common performance tricks between JavaScript, Java and other languages.

提交回复
热议问题