How to return multiple arrays from a function in Javascript?

房东的猫 提交于 2019-12-21 04:11:12

问题


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 ????

}

回答1:


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



回答2:


Simply put your arrays into an array and return it I guess.




回答3:


I would suggest making an array of arrays. In other words, a multidimensional array. That way, you can reference all arrays outside of the function within that one returned array. To learn more on how to do this, this link is quite useful: http://sharkysoft.com/tutorials/jsa/content/019.html



来源:https://stackoverflow.com/questions/5760058/how-to-return-multiple-arrays-from-a-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!