简体   繁体   中英

I have an 'n' number of array and how can I concat all array into a single array using jQuery

How can I concat 'n' number of arrays into a single array using jQuery.

     a1 = [a,b,c,d,f];
     a2 = [h,g,f,r];
     ...............
     an = [r,e,c,g,s,g];

and I need to get like

     A = [a,b,c,d,f,h,g,f,r,.....,r,e,c,g,s,g];

Please help. Thank you in advance for all replay

You're looking for array concat method

jsBin demo

var arr1 = ["a", "b"];
var arr2 = ["c", "d"];

var arr3 = arr1.concat(arr2);

console.log(arr3);  // ["a", "b", "c", "d"]

You can find more info here:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/concat

var A=a1.concat(a2,a3,a4,....,an);

Assuming your arrays are all named a<x> , and global variables, you can loop through them on the window object as follows:

var output = [];
for(var i = 1; window['a'+i]; i++){
    output = output.concat(window['a'+i]);
}

Working example

Output will then, at the end of the loop, be a concatenation of all the arrays.

window['a'+i] will refer to the a1 - aX arrays, since global variables are properties of the window object. As such, these are all identical:

var output = "Some content"

console.log(output);
console.log(window.output);
console.log(window['output']);
// These will all return "Some content"

You can also manually concatenate them like this if you know how many you have:

output = a1.concat(a2,a3,a<x>...);
Array.prototype.concat([1,2,3],[4,5])

要么

[1,2,3].concat([4,5])

Try with $.merge; example:

var new = $.merge( [0,1,2], [2,3,4] ); // new = [0,1,2,2,3,4]

Use concat() method.

var a1 = ["a","b","c","d","f"]; 
var a2 = ["h","g","f","r"]

var a3 = a1.concat(a2);

console.log(a3);  // Outputs: ["a", "b", "c", "d", "f", "h", "g", "f", "r"]

您可以使用标准功能concat

Something similar to:

for(a2...an){
    a1 = $.merge(a1,next);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM