如何在JavaScript中将对象(如字符串或数字)附加到数组中?


当前回答

您可以使用push方法。

Array.prototype.append = function(destArray){
    destArray = destArray || [];
    this.push.call(this, ...destArray);
    return this;
}
var arr = [1,2,5,67];
var arr1 = [7,4,7,8];
console.log(arr.append(arr1)); // [7, 4, 7, 8, 1, 4, 5, 67, 7]
console.log(arr.append("Hola")) // [1, 2, 5, 67, 7, 4, 7, 8, "H", "o", "l", "a"]

其他回答

使用凹面:

a=[1,2,3];b=[3,4,5];a=混凝土(b);控制台日志(a);

如果要添加值,可以使用push(),例如arr.push(“测试1”、“测试2”);。

如果您有数组,可以使用concat(),例如Array1.contat(Array2)。

如果只有一个元素要添加,也可以尝试长度方法,例如array[aray.length]=“test”;。

当然,concat()也可以用于二维数组。无需循环。

var a = [
    [1, 2],
    [3, 4] ];

var b = [
    ["a", "b"],
    ["c", "d"] ];

b = b.concat(a);

alert(b[2][1]); // Result: 2

附加单个元素

// Append to the end
arrName.push('newName1');

// Prepend to the start
arrName.unshift('newName1');

// Insert at index 1
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element


// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';

附加多个元素

// Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where insert starts,
// 0: number of element to remove,
//newElemenet1,2,3: new elements

附加一个数组

// Join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array

让数组长度属性执行以下操作:

myarray[myarray.length] = 'new element value added to the end of the array';

myarray.length返回数组中的字符串数。JavaScript是从零开始的,因此数组的下一个元素键将是数组的当前长度。

例子:

var myarray = [0, 1, 2, 3],
    myarrayLength = myarray.length; // myarrayLength is set to 4