Hot For Coding

JavaScript数组拼接

在JavaScript中数组拼接有几种方式

遍历拼接

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

for (var i = 0; i < arr2.length; i += 1) {
  arr1.push(arr2[i]);
}

console.log(arr1); // Output: (6) ["a", "b", "c", "d", "e", "f"]

这种方式比较灵活控制,比如去重

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

for (var i = 0; i < arr2.length; i += 1) {
  if (arr1.indexOf(arr2[i]) === -1) {
    arr1.push(arr2[i]);
  }
}

console.log(arr1); // Output: (5) ["a", "b", "c", "d", "e"]

你也可以不改变原数组,也可以这样去重

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

var arr3 = [];

var push = function (getArr, writeArr) {
  for (var i = 0; i < getArr.length; i += 1) {
    if (writeArr.indexOf(getArr[i]) === -1) {
      writeArr.push(getArr[i]);
    }
  }
}

push(arr1, arr3);
push(arr2, arr3);

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

使用concat

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

console.log(arr1); // Output: (3) ["a", "b", "c"]
console.log(arr2); // Output: (3) ["d", "e", "f"]
console.log(arr3); // Output: (6) ["a", "b", "c", "d", "e", "f"]

这种方式不改变原数组,但不会去重

var arr1 = ['a', 'b', 'c', 'c'];
var arr2 = ['a', 'd', 'e', 'f'];

var arr3 = arr1.concat(arr2);

console.log(arr1); // Output: (4) ["a", "b", "c", "c"]
console.log(arr2); // Output: (4) ["a", "d", "e", "f"]
console.log(arr3); // Output: (8) ["a", "b", "c", "c", "a", "d", "e", "f"]
分享

TITLE: JavaScript数组拼接

LINK: https://www.qttc.net/243-javascript-array-concat.html

NOTE: 原创内容,转载请注明出自琼台博客