最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript How Array.prototype.push concatenates - Stack Overflow

programmeradmin3浏览0评论

I've seen the Array's push method used to replace concatenation, but I'm not entirely sure how it works.

var a = [1,2,3];
var b = [4,5,6];
Array.prototype.push.apply(a,b);

How does this concatenate in place rather than returning a new array?

I've seen the Array's push method used to replace concatenation, but I'm not entirely sure how it works.

var a = [1,2,3];
var b = [4,5,6];
Array.prototype.push.apply(a,b);

How does this concatenate in place rather than returning a new array?

Share Improve this question asked Dec 26, 2012 at 22:36 Jeff StoreyJeff Storey 57.2k74 gold badges242 silver badges412 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 15

.apply() takes two arguments:

fun.apply(thisArg[, argsArray])

You're passing a as your this object and b as your argument list, so your code is really calling .push() with the elements of b as your arguments:

var a = [1, 2, 3];
a.push(4, 5, 6);

Now, .push() just mutates your original array.

Using this. To try to describe it see this customPush function.

function customPush() {
    var i = 0,
        len = arguments.length;

    for(; i < len; i++) {
        this[this.length] = arguments[i];
    }
};


var a = [1,2,3];
var b = [4,5,6];
customPush.apply(a,b);
发布评论

评论列表(0)

  1. 暂无评论