How to extend an existing JavaScript array with an

2018-12-31 20:58发布

There doesn't seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python's extend method.

I want to achieve the following:

>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
>>> a
[1, 2, 3, 4, 5]

I know there's a a.concat(b) method, but it creates a new array instead of simply extending the first one. I'd like an algorithm that works efficiently when a is significantly larger than b (i.e. one that does not copy a).

Note: This is not a duplicate of How to append something to an array? -- the goal here is to add the whole contents of one array to the other, and to do it "in place", i.e. without copying all elements of the extended array.

14条回答
若你有天会懂
2楼-- · 2018-12-31 21:32

You should use a loop-based technique. Other answers on this page that are based on using .apply can fail for large arrays.

A fairly terse loop-based implementation is:

Array.prototype.extend = function (other_array) {
    /* You should include a test to check whether other_array really is an array */
    other_array.forEach(function(v) {this.push(v)}, this);
}

You can then do the following:

var a = [1,2,3];
var b = [5,4,3];
a.extend(b);

DzinX's answer (using push.apply) and other .apply based methods fail when the array that we are appending is large (tests show that for me large is > 150,000 entries approx in Chrome, and > 500,000 entries in Firefox). You can see this error occurring in this jsperf.

An error occurs because the call stack size is exceeded when 'Function.prototype.apply' is called with a large array as the second argument. (MDN has a note on the dangers of exceeding call stack size using Function.prototype.apply - see the section titled "apply and built-in functions".)

For a speed comparison with other answers on this page, check out this jsperf (thanks to EaterOfCode). The loop-based implementation is similar in speed to using Array.push.apply, but tends to be a little slower than Array.slice.apply.

Interestingly, if the array you are appending is sparse, the forEach based method above can take advantage of the sparsity and outperform the .apply based methods; check out this jsperf if you want to test this for yourself.

By the way, do not be tempted (as I was!) to further shorten the forEach implementation to:

Array.prototype.extend = function (array) {
    array.forEach(this.push, this);
}

because this produces garbage results! Why? Because Array.prototype.forEach provides three arguments to the function it calls - these are: (element_value, element_index, source_array). All of these will be pushed onto your first array for every iteration of forEach if you use "forEach(this.push, this)"!

查看更多
倾城一夜雪
3楼-- · 2018-12-31 21:32

You can create a polyfill for extend as I have below. It will add to the array; in-place and return itself, so that you can chain other methods.

if (Array.prototype.extend === undefined) {
  Array.prototype.extend = function(other) {
    this.push.apply(this, arguments.length > 1 ? arguments : other);
    return this;
  };
}

function print() {
  document.body.innerHTML += [].map.call(arguments, function(item) {
    return typeof item === 'object' ? JSON.stringify(item) : item;
  }).join(' ') + '\n';
}
document.body.innerHTML = '';

var a = [1, 2, 3];
var b = [4, 5, 6];

print('Concat');
print('(1)', a.concat(b));
print('(2)', a.concat(b));
print('(3)', a.concat(4, 5, 6));

print('\nExtend');
print('(1)', a.extend(b));
print('(2)', a.extend(b));
print('(3)', a.extend(4, 5, 6));
body {
  font-family: monospace;
  white-space: pre;
}

查看更多
唯独是你
4楼-- · 2018-12-31 21:33

Combining the answers...

Array.prototype.extend = function(array) {
    if (array.length < 150000) {
        this.push.apply(this, array)
    } else {
        for (var i = 0, len = array.length; i < len; ++i) {
            this.push(array[i]);
        };
    }  
}
查看更多
永恒的永恒
5楼-- · 2018-12-31 21:42

If you want to use jQuery, there is $.merge()

Example:

a = [1, 2];
b = [3, 4, 5];
$.merge(a,b);

Result: a = [1, 2, 3, 4, 5]

查看更多
只靠听说
6楼-- · 2018-12-31 21:44

It is possible to do it using splice():

b.unshift(b.length)
b.unshift(a.length)
Array.prototype.splice.apply(a,b) 
b.shift() // Restore b
b.shift() // 

But despite being uglier it is not faster than push.apply, at least not in Firefox 3.0.

查看更多
美炸的是我
7楼-- · 2018-12-31 21:46

I like the a.push.apply(a, b) method described above, and if you want you can always create a library function like this:

Array.prototype.append = function(array)
{
    this.push.apply(this, array)
}

and use it like this

a = [1,2]
b = [3,4]

a.append(b)
查看更多
登录 后发表回答