简体   繁体   English

我有一个n个数组,如何使用jQuery将所有数组合并为一个数组

[英]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. 我如何使用jQuery将n个数组合并为一个数组。

     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 您正在寻找array concat方法

jsBin demo jsBin演示

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 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: 假设所有数组均名为a<x>和全局变量,则可以在window对象上循环遍历它们,如下所示:

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. window['a'+i]将引用a1 - aX数组,因为全局变量是window对象的属性。 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; 尝试$ .merge; example: 例:

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

Use concat() method. 使用concat()方法。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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