如何在JavaScript中将对象(如字符串或数字)附加到数组中?
当前回答
让数组长度属性执行以下操作:
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
其他回答
现在大多数浏览器都支持ECMAScript 5(ES5)标准的JavaScript,您可以使用apply()将array1附加到array2。
var array1 = [3, 4, 5];
var array2 = [1, 2];
Array.prototype.push.apply(array2, array1);
console.log(array2); // [1, 2, 3, 4, 5]
带有ECMAScript 6(ES6)标准的JavaScript,Chrome、Firefox、Internet Explorer和Edge支持该标准,您可以使用扩展运算符:
"use strict";
let array1 = [3, 4, 5];
let array2 = [1, 2];
array2.push(...array1);
console.log(array2); // [1, 2, 3, 4, 5]
排列运算符将替换array2.push(…array1);带有阵列2.推(3,4,5);当浏览器思考逻辑时。
加分
如果要创建另一个变量来存储两个数组中的所有项,可以执行以下操作:
ES5 var combinedArray=array1.concat(array2);
ES6常量组合数组=[…array1,…array2]
扩展运算符(…)用于扩展集合中的所有项目。
如果arr是数组,而val是要添加的值,请使用:
arr.push(val);
E.g.
var arr=[‘a’,‘b’,‘c’];arr.push('d');控制台日志(arr);
附加单个元素
// 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
有两种方法可以在JavaScript中附加数组:
1) push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。
var a = [1, 2, 3];
a.push(4, 5);
console.log(a);
输出:
[1, 2, 3, 4, 5]
2) unshift()方法将一个或多个元素添加到数组的开头,并返回数组的新长度:
var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a);
输出:
[4, 5, 1, 2, 3]
3) concat()方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);
输出:
[ "a", "b", "c", "d", "e", "f" ]
4) 可以使用数组的.length属性将元素添加到数组的末尾:
var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar );
输出:
["one", "two", "three", "four"]
5) splice()方法通过删除现有元素和/或添加新元素来更改数组的内容:
var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);
输出:
["angel", "clown", "mandarin", "surgeon","nemo"]
6) 您还可以通过指定新索引并赋值来向数组中添加新元素:
var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);
输出:
["one", "two","three","four"]