How to return values in javascript

后端 未结 8 2054
孤独总比滥情好
孤独总比滥情好 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:02

    You can return an array, an object literal, or an object of a type you created that encapsulates the returned values.

    Then you can pass in the array, object literal, or custom object into a method to disseminate the values.

    Object example:

    function myFunction(value1,value2,value3)
    {
         var returnedObject = {};
         returnedObject["value1"] = value1;
         returnedObject["value2"] = value2;
         return returnedObject;
    }
    
    var returnValue = myFunction("1",value2,value3);
    
    if(returnValue.value1  && returnValue.value2)
    {
    //Do some stuff
    }
    

    Array example:

    function myFunction(value1,value2,value3)
    {
         var returnedArray = [];
         returnedArray.push(value1);
         returnedArray.push(value2);
         return returnedArray;
    }
    
    var returnValue = myFunction("1",value2,value3);
    
    if(returnValue[0]  && returnValue[1])
    {
    //Do some stuff
    }
    

    Custom Object:

    function myFunction(value1,value2,value3)
    {
         var valueHolder = new ValueHolder(value1, value2);
         return valueHolder;
    }
    
    var returnValue = myFunction("1",value2,value3);
    
    // hypothetical method that you could build to create an easier to read conditional 
    // (might not apply to your situation)
    if(returnValue.valid())
    {
    //Do some stuff
    }
    

    I would avoid the array method because you would have to access the values via indices rather than named object properties.

提交回复
热议问题