Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple arrays from a function in Javascript?

I have multiple arrays in a function that I want to use in another function. How can I return them to use in another function

this.runThisFunctionOnCall = function(){


    array1;
    array2;
    array3;

    return ????

}
like image 637
Asim Zaidi Avatar asked Apr 22 '11 21:04

Asim Zaidi


People also ask

How do I return multiple arrays?

JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.

Can a method return multiple arrays?

You can return only one value in Java. If needed you can return multiple values using array or an object.

How can I return multiple values from a function?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data.

Can you have multiple return statements JavaScript?

A function can have more than one return statement, but only ever run one based on a condition.


1 Answers

as an array ;)

this.runThisFunctionOnCall = function(){
    var array1 = [11,12,13,14,15];
    var array2 = [21,22,23,24,25];
    var array3 = [31,32,33,34,35];

    return [
     array1,
     array2,
     array3
    ];
}

call it like:

 var test =  this.runThisFunctionOnCall();
 var a = test[0][0] // is 11
 var b = test[1][0] // is 21
 var c = test[2][1] // is 32

or an object:

this.runThisFunctionOnCall = function(){
    var array1 = [11,12,13,14,15];
    var array2 = [21,22,23,24,25];
    var array3 = [31,32,33,34,35];

    return {
     array1: array1,
     array2: array2,
     array3: array3
    };
}

call it like:

 var test =  this.runThisFunctionOnCall();
 var a = test.array1[0] // is 11
 var b = test.array2[0] // is 21
 var c = test.array3[1] // is 32
like image 124
Caspar Kleijne Avatar answered Sep 19 '22 17:09

Caspar Kleijne