Javascript 如何使用 jQuery 将数组添加到数组数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3691974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:43:22  来源:igfitidea点击:

How can I add an array to an array of arrays using jQuery?

javascriptjqueryarrays

提问by David says reinstate Monica

I have an array, as below:

我有一个数组,如下所示:

var cString =   [
            ['1','Techdirt','www.techdirt.com'],
            ['2','Slashdot','slashdot.org'],
            ['3','Wired','wired.com']
            ];

to this array I want to add another in the same format:

我想以相同的格式向这个数组添加另一个:

var test = ['4','Stackoverflow','stackoverflow.com']

I've tried using:

我试过使用:

var newArray = $.merge(cString, test);

But console.log(newArray);outputs:

console.log(newArray);输出:

[?Array,?Array,?Array,'4','Stackoverflow','stackoverflow.com']

So I'm assumingthat I'm missing something obvious. Or attempting something stupid...help?

所以我假设我遗漏了一些明显的东西。或者尝试一些愚蠢的事情......帮助?

回答by user113716

jQuery is not needed for this. Just use the Array's .push()methodto add it to the main array.

为此不需要 jQuery。只需使用Array 的.push()方法将其添加到主数组。

var test = ['4','Stackoverflow','stackoverflow.com']

cString.push( test );

What $.merge()does is it walks through the second array you pass it and copies its items one by one into the first.

什么$.merge()确实是走过你通过它并复制其项目一个一个地进入第一第二阵列。



EDIT:

编辑:

If you didn't want to modify the original array, you could make a copy of it first, and .push()the new Array into the copy.

如果不想修改原数组,可以先复制一份,.push()新数组放入副本。

var cString =   [
            ['1','Techdirt','www.techdirt.com'],
            ['2','Slashdot','slashdot.org'],
            ['3','Wired','wired.com']
            ];

var test = ['4','Stackoverflow','stackoverflow.com']

var newArray = cString.slice();

newArray.push( test );

回答by bobince

In addition to pushas described by patrick, if you want to create a newlist rather than changing the old, you can add arrays together with Array#concat:

除了pushpatrick 所描述的,如果您想创建一个列表而不是更改旧列表,您可以将数组添加到一起Array#concat

var newArray= cString.concat([['4','Stackoverflow','stackoverflow.com']]);

回答by Anbu

you can use merge function like this

你可以像这样使用合并功能

var newArray = $.merge($.merge([], cString), test);