How to return values in javascript

后端 未结 8 1946
孤独总比滥情好
孤独总比滥情好 2020-11-27 04:47

I have a javascript function:

function myFunction(value1,value2,value3)
{
     //Do stuff and 

     value2=somevalue2 //to return
     value3=somevalue3 //t         


        
相关标签:
8条回答
  • 2020-11-27 05:18

    The answers cover things very well. I just wanted to point out that the mechanism of out parameters, as described in the question isn't very javascriptish. While other languages support it, javascript prefers you to simply return values from functions.

    With ES6/ES2015 they added destructuring that makes a solution to this problem more elegant when returning an array. Destructuring will pull parts out of an array/object:

    function myFunction(value1)
    {
        //Do stuff and 
        return [somevalue2, sumevalue3]
    }
    
    var [value2, value3] = myFunction("1");
    
    if(value2  && value3)
    {
        //Do some stuff
    }
    
    0 讨论(0)
  • 2020-11-27 05:27

    I would prefer a callback solution: Working fiddle here: http://jsfiddle.net/canCu/

    function myFunction(value1,value2,value3, callback) {
    
        value2 = 'somevalue2'; //to return
        value3 = 'somevalue3'; //to return
    
        callback( value2, value3 );
    
    }
    
    var value1 = 1;
    var value2 = 2;
    var value3 = 3;
    
    myFunction(value1,value2,value3, function(value2, value3){
        if (value2 && value3) {
            //Do some stuff
            alert( value2 + '-' + value3 );
        }    
    });
    
    0 讨论(0)
提交回复
热议问题