热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Javascript将数组值推入另一个数组。-Javascriptpusharrayvaluesintoanotherarray

IhaveajavascriptarraydataArraywhichIwanttopushintoanewarraynewArray.ExceptIdontw

I have a Javascript array dataArray which I want to push into a new array newArray. Except I don't want newArray[0] to be dataArray. I want to push in all the values into the new array:

我有一个Javascript数组dataArray我想把它推入一个新的数组newArray。除非我不想让newArray[0]成为dataArray。我想把所有的值都推到新数组中:

var newArray = [];

newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...

or even better:

或者更好的是:

var newArray = new Array (
   dataArray1.values(),
   dataArray2.values(),
   // ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself
);

So now the new array contains all the values of the individual data arrays. Is there some shorthand like pushValues available so I don't have to iterate over each individual dataArray, adding the values 1 by 1?

现在,新数组包含了各个数据数组的所有值。是否有一些类似pushValues的简写方式,这样我就不必遍历每个单独的dataArray,并将值1加1?

13 个解决方案

#1


815  

Use the concat function, like so:

使用concat函数,如下所示:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).

newArray的值为[1,2,3,4](arrayA和arrayB不变;concat为结果创建并返回一个新数组。

#2


565  

Provided your arrays are not huge (see caveat below), you can use the push() method of the array to which you wish to append values. push() can take multiple parameters so you can use its apply() method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat() of adding elements to the array in place rather than creating a new array.

如果您的数组不是很大(请参阅下面的说明),您可以使用您希望添加值的数组的push()方法。push()可以使用多个参数,因此您可以使用它的apply()方法来传递值的数组作为函数参数的列表。这比使用concat()将元素添加到数组中而不是创建一个新数组具有优势。

However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100 for details.

然而,对于大型数组(100,000个成员或更多的成员)来说,这个技巧可能会失败。对于这样的数组,使用循环是更好的方法。有关详细信息,请参阅https://stackoverflow.com/a/17368101/96100。

var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);

You might want to generalize this into a function:

你可能想把它归纳成一个函数:

function pushArray(arr, arr2) {
    arr.push.apply(arr, arr2);
}

... or add it to Array's prototype:

…或者将其添加到Array的原型中:

Array.prototype.pushArray = function(arr) {
    this.push.apply(this, arr);
};

var newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);

... or emulate the original push() method by allowing multiple parameters using the fact that concat(), like push(), allows multiple parameters:

…或者模拟原始的push()方法,允许多个参数使用concat()和push()这样的事实,允许多个参数:

Array.prototype.pushArray = function() {
    this.push.apply(this, this.concat.apply([], arguments));
};

var newArray = [];
newArray.pushArray(dataArray1, dataArray2);

Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:

这里是最后一个示例的循环版本,适用于大型数组和所有主流浏览器,包括IE <= 8:

Array.prototype.pushArray = function() {
    var toPush = this.concat.apply([], arguments);
    for (var i = 0, len = toPush.length; i 

#3


182  

I will add one more "future-proof" reply

我将再添加一个“未来证明”的回复。

In ECMAScript 6, you can use the spread operator:

在ECMAScript 6中,可以使用扩展操作符:

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);

Spread operator is not yet included in all major browsers. For the current compatibility, see this (continuously updated) compatibility table.

扩展操作符还没有包含在所有主流浏览器中。对于当前的兼容性,请参见这个(不断更新的)兼容表。

You can, however, use spread operator with Babel.js.

但是,您可以使用Babel.js扩展操作符。

#4


118  

Found an elegant way from MDN

从MDN找到了一种优雅的方式。

var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];

// Merge the second array into the first one
// Equivalent to vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

Or you can use the spread operator feature of ES6:

或者您可以使用ES6的扩展操作符特性:

let fruits = [ 'apple', 'banana'];
const moreFruits = [ 'orange', 'plum' ];

fruits.push(...moreFruits); // ["apple", "banana", "orange", "plum"]

#5


11  

var a=new Array('a','b','c');
var b=new Array('d','e','f');
var d=new Array('x','y','z');
var c=a.concat(b,d)

Does that solve your problem ?

这能解决你的问题吗?

#6


6  

With Javascript ES6, you can use the ... operator as a spread operator which will essentially convert the array into values. Then, you can do something like this:

使用Javascript ES6,您可以使用…操作符作为一个扩展运算符,它将把数组转换成值。然后,你可以这样做:

var myArray = [1,2,3,4,5];
var moreData = [6,7,8,9,10];

myArray = [
  ...myArray,
  ...moreData,
];

While the syntax is concise, I do not know how this works internally and what the performance implications are on large arrays.

虽然语法很简洁,但我不知道这在内部是如何工作的,以及对大型数组的性能影响。

#7


6  

There are a number of answers talking about Array.prototype.push.apply. Here is a clear example:

这里有很多关于Array.prototype.push.apply的答案。这里有一个明显的例子:

var dataArray1 = [1, 2];
var dataArray2 = [3, 4, 5];
var newArray = [ ];
Array.prototype.push.apply(newArray, dataArray1); // newArray = [1, 2]
Array.prototype.push.apply(newArray, dataArray2); // newArray = [1, 2, 3, 4, 5]
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]

If you have ES6 syntax:

如果你有ES6语法:

var dataArray1 = [1, 2];
var dataArray2 = [3, 4, 5];
var newArray = [ ];
newArray.push(...dataArray1); // newArray = [1, 2]
newArray.push(...dataArray2); // newArray = [1, 2, 3, 4, 5]
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]

#8


5  

The function below doesn't have an issue with the length of arrays and performs better than all suggested solutions:

下面的函数与数组的长度无关,比所有建议的解决方案都要好:

function pushArray(list, other) {
    var len = other.length;
    var start = list.length;
    list.length = start + len;
    for (var i = 0; i 

unfortunately, jspref refuses to accept my submissions, so here they are the results using benchmark.js

不幸的是,jspref拒绝接受我的提交,所以这里是使用基准测试的结果。

        Name            |   ops/sec   |  ± %  | runs sampled
for loop and push       |      177506 |  0.92 | 63
Push Apply              |      234280 |  0.77 | 66
spread operator         |      259725 |  0.40 | 67
set length and for loop |      284223 |  0.41 | 66

where

在哪里

for loop and push is:

for循环和push是:

    for (var i = 0, l = source.length; i 

Push Apply:

推动应用:

target.push.apply(target, source);

spread operator:

接线员:传播

    target.push(...source);

and finally the 'set length and for loop' is the above function

最后,“设置长度和for循环”是上述函数。

#9


4  

The following seems simplest to me:

下面的例子对我来说是最简单的:

var newArray = dataArray1.slice();
newArray.push.apply(newArray, dataArray2);

As "push" takes a variable number of arguments, you can use the apply method of the push function to push all of the elements of another array. It constructs a call to push using its first argument ("newArray" here) as "this" and the elements of the array as the remaining arguments.

当“push”接受变量数量的参数时,您可以使用push函数的apply方法来推动另一个数组的所有元素。它构造一个调用来使用它的第一个参数(这里的“newArray”)作为“this”,以及数组的元素作为剩余的参数。

The slice in the first statement gets a copy of the first array, so you don't modify it.

第一个语句中的切片获取第一个数组的副本,因此您不修改它。

Update If you are using a version of Javascript with slice available, you can simplify the push expression to:

如果您正在使用一个可用slice提供的Javascript版本,您可以将push表达式简化为:

newArray.push(...dataArray2)

#10


1  

We have two array a and b. the code what did here is array a value is pushed into array b.

我们有两个数组a和b,这里的代码是数组a值被推送到数组b中。

let a = [2, 4, 6, 8, 9, 15]

function transform(a) {
    let b = ['4', '16', '64']
    a.forEach(function(e) {
        b.push(e.toString());
    });
    return b;
}

transform(a)

[ '4', '16', '64', '2', '4', '6', '8', '9', '15' ]

#11


-3  

instead of push() function use concat function for IE. example,

使用concat函数代替push()函数。的例子,

var a=a.concat(a,new Array('amin'));

#12


-3  

Тhis is a working code and it works fine:

他的工作守则是可行的:

var els = document.getElementsByTagName('input'), i;
var invnum = new Array();
var k = els.length;
for(i = 0; i 

#13


-4  

Most simple:

最简单的:

var newArray = dataArray1.slice(0);

推荐阅读
  • 本文介绍了闭包的定义和运转机制,重点解释了闭包如何能够接触外部函数的作用域中的变量。通过词法作用域的查找规则,闭包可以访问外部函数的作用域。同时还提到了闭包的作用和影响。 ... [详细]
  • VueCLI多页分目录打包的步骤记录
    本文介绍了使用VueCLI进行多页分目录打包的步骤,包括页面目录结构、安装依赖、获取Vue CLI需要的多页对象等内容。同时还提供了自定义不同模块页面标题的方法。 ... [详细]
  • Ihaveaforminadirectivetemplate:我在指令模板中有一个表单:<formn ... [详细]
  • 本文介绍了PE文件结构中的导出表的解析方法,包括获取区段头表、遍历查找所在的区段等步骤。通过该方法可以准确地解析PE文件中的导出表信息。 ... [详细]
  • 本文介绍了在wepy中运用小顺序页面受权的计划,包含了用户点击作废后的从新受权计划。 ... [详细]
  • 本文介绍了使用哈夫曼树实现文件压缩和解压的方法。首先对数据结构课程设计中的代码进行了分析,包括使用时间调用、常量定义和统计文件中各个字符时相关的结构体。然后讨论了哈夫曼树的实现原理和算法。最后介绍了文件压缩和解压的具体步骤,包括字符统计、构建哈夫曼树、生成编码表、编码和解码过程。通过实例演示了文件压缩和解压的效果。本文的内容对于理解哈夫曼树的实现原理和应用具有一定的参考价值。 ... [详细]
  • 一、什么是闭包?有什么作用什么是闭包闭包是定义在一个函数内部的函数,它可以访问父级函数的内部变量。当一个闭包被创建时,会关联一个作用域—— ... [详细]
  • SoIhavealoopthatrunsperfectforeventsandonlyshowsfutureposts.TheissueisthatIwould ... [详细]
  • 1.{#if}{#if|COND|}..{#elseif|COND|}..{#else}..{#if}Examples:{#if2*816}good{#else}fa ... [详细]
  • 动态规划算法的基本步骤及最长递增子序列问题详解
    本文详细介绍了动态规划算法的基本步骤,包括划分阶段、选择状态、决策和状态转移方程,并以最长递增子序列问题为例进行了详细解析。动态规划算法的有效性依赖于问题本身所具有的最优子结构性质和子问题重叠性质。通过将子问题的解保存在一个表中,在以后尽可能多地利用这些子问题的解,从而提高算法的效率。 ... [详细]
  • 本文介绍了指针的概念以及在函数调用时使用指针作为参数的情况。指针存放的是变量的地址,通过指针可以修改指针所指的变量的值。然而,如果想要修改指针的指向,就需要使用指针的引用。文章还通过一个简单的示例代码解释了指针的引用的使用方法,并思考了在修改指针的指向后,取指针的输出结果。 ... [详细]
  • Linux环境变量函数getenv、putenv、setenv和unsetenv详解
    本文详细解释了Linux中的环境变量函数getenv、putenv、setenv和unsetenv的用法和功能。通过使用这些函数,可以获取、设置和删除环境变量的值。同时给出了相应的函数原型、参数说明和返回值。通过示例代码演示了如何使用getenv函数获取环境变量的值,并打印出来。 ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • php禁止ip访问,php限制ip访问
    本文目录一览:1、求一段PHP限制IP及IP段访问的代码,拜托了。。 ... [详细]
  • unitUnit1;interfaceusesWinapi.Windows,Winapi.Messages,System.SysUtils,System.Variants,Syst ... [详细]
author-avatar
5257wals_220
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有