js数组合并的几种方法

  1. concat 方法
	var arr1 = [1, 2, 3];
	var arr2 = ['a', 'b', 'c'];
	var newArr = arr1.concat(arr2);
	console.log(newArr);// [1, 2, 3, "a", "b", "c"]
	console.log(arr1 );// [1, 2, 3] 

利用concat方法会产生一个新的数组,不会改变原有的数组.

  1. 循环遍历
	var arr1 = [1, 2, 3]
    var arr2 = ['a', 'b', 'c']
    for (var i = 0; i < arr2.length; i++) {
      arr1.push(arr2[i])
    }
    console.log(arr1);//[1, 2, 3, "a", "b", "c"]
  1. apply
    合并数组arr1和数组arr2,使用arr1.push.apply(arr1,arr2);
	var arr1 = [1, 2, 3]
    var arr2 = ['a', 'b', 'c']
	arr1.push.apply(arr1,arr2);
	console.log(arr1) //[1, 2, 3, "a", "b", "c"]
  1. ES6语法: …操作符
	var arr1 = [1, 2, 3]
    var arr2 = ['a', 'b', 'c']
	var newArr = [...arr1, ...arr2]; //[1, 2, 3, "a", "b", "c"];

你可能感兴趣的:(前端知识点总结)