admin管理员组

文章数量:1277345

Imagine I've got two arrays in JavaScript:

var geoff = ['one', 'two'];
var degeoff = ['three', 'four'];

How do I merge the two arrays, resulting in an array like this?

var geoffdegeoff = ['one', 'two', 'three', 'four'];

Imagine I've got two arrays in JavaScript:

var geoff = ['one', 'two'];
var degeoff = ['three', 'four'];

How do I merge the two arrays, resulting in an array like this?

var geoffdegeoff = ['one', 'two', 'three', 'four'];
Share Improve this question edited Feb 25, 2014 at 13:39 George Stocker 57.9k29 gold badges181 silver badges238 bronze badges asked Aug 26, 2009 at 16:18 Paul D. WaitePaul D. Waite 98.9k57 gold badges202 silver badges271 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 15
var geoffdegeoff = geoff.concat(degeoff);

I stumbled across this and thought to add an additional way.

note: I see you want to create a third new var.

.concat is good, but you have to create a new array (unless you override the orig).

How about if you want to merge/bine array "second" into array "first".

Here is a nifty way.

// using apply
var first = ['aa','bb','cc'];
var second = ['dd','ee'];
first.push.apply(first, second);
first;

or

Array.prototype.push.apply(first, second); 
first;

本文标签: How do I merge two arrays to create one array in JavaScriptStack Overflow