>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
>>> a
[1, 2, 3, 4, 5]
>>> a.push(...b)
>>> a.push.apply(a, b)
>>> Array.prototype.push.apply(a,b)
var a = [1, 2, 3];
a = a.concat([5, 4, 3]);
const a = [1, 2, 3];
const b = [...a, 5, 4, 3];
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);
}
var a = [1,2,3];
var b = [5,4,3];
a.extend(b);
Array.prototype.extend = function (array) {
array.forEach(this.push, this);
}
arr1.push(...arr2);
var a = [1, 2, 3, 4];
var b = [5, 6, 7];
Array.prototype.push.apply(a, b);
a = [1, 2, 3, 4, 5, 6, 7];
a.push(...b); //a = [1, 2, 3, 4, 5, 6, 7];
while(b.length) {
a.push(b.shift());
}
a = [1, 2, 3, 4, 5, 6, 7];
b = [];
a = [1, 2];
b = [3, 4, 5];
$.merge(a,b);
Array.prototype.append = function(array)
{
this.push.apply(this, array)
}
a = [1,2]
b = [3,4]
a.append(b)
b.unshift(b.length)
b.unshift(a.length)
Array.prototype.splice.apply(a,b)
b.shift() // Restore b
b.shift() //
此解决方案对我有用(使用 ECMAScript 6 的传播运算符):
let array = ['my', 'solution', 'works'];
let newArray = [];
let newArray2 = [];
newArray.push(...array); // Adding to same array
newArray2.push([...array]); // Adding as child/leaf/sub-array
console.log(newArray);
console.log(newArray2);
您可以按照下面的方法创建一个 polyfill 进行扩展。它将添加到数组;就位并返回自身,以便可以链接其他方法。
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;
}