Array.prototype.concat()

concat()方法用于合并两个或多个数组。

此方法不改变原数组,而是返回一个新数组。

参数是数组或者值,返回值是新数组。

concat方法不会改变this或任何作为参数提供的数组,而是返回一个浅拷贝,因此要注意引用类型的数据如果其属性改变,对于原数组和新数组都是可见的。

var alpha = ['a', 'b', 'c'];
var numeric = [1, 2, 3];

alpha.concat(numeric);
// result in ['a', 'b', 'c', 1, 2, 3]



var num1 = [1, 2, 3],
    num2 = [4, 5, 6],
    num3 = [7, 8, 9];

var nums = num1.concat(num2, num3);

console.log(nums); 
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]



var alpha = ['a', 'b', 'c'];

var alphaNumeric = alpha.concat(1, [2, 3]);

console.log(alphaNumeric); 
// results in ['a', 'b', 'c', 1, 2, 3]



var num1 = [[1]];
var num2 = [2, [3]];

var nums = num1.concat(num2);

console.log(nums);
// results in [[1], 2, [3]]

// modify the first element of num1
num1[0].push(4);

console.log(nums);
// results in [[1, 4], 2, [3]]

自己实现简单的concat():

 

Array.prototype.concat = function () {
    var res = [];

    res.push.apply(res, this);

    for (var i = 0; i < arguments.length; i++) {
        if (Object.prototype.toString.call(arguments[i]) == '[object Array]') {
            res.push.apply(res, arguments[i]);
        } else {
            res.push.call(res, arguments[i]);
        }
    }

    return res;
}

 

posted @ 2018-06-25 10:05  hahazexia  阅读(1002)  评论(0)    收藏  举报