var arr = ["apple","banana","cherry"];
// Do not forget to assign the result as, unlike push, concat does not change the existing arrayarr = arr.concat(["dragonfruit","elderberry","fig"]);
console.log(arr);
var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.push("Kiwi");
// The result of fruits will be:Banana, Orange, Apple, Mango, Kiwi
你的问题的确切答案已经回答了,但是让我们看看向数组添加项目的其他一些方法。
unshift()方法将新项目添加到数组的开头,并返回新长度。例子:
var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.unshift("Lemon", "Pineapple");
// The result of fruits will be:Lemon, Pineapple, Banana, Orange, Apple, Mango
最后,concat()方法用于连接两个或多个数组。例子:
var fruits = ["Banana", "Orange"];var moreFruits = ["Apple", "Mango", "Lemon"];var allFruits = fruits.concat(moreFruits);
// The values of the children array will be:Banana, Orange, Apple, Mango, Lemon
// Initialize the array
var arr = ["Hi","Hello","Bangladesh"];
// Append a new value to the array
arr = [...arr, "Feni"];
// Or you can add a variable value
var testValue = "Cool";
arr = [...arr, testValue ];
console.log(arr);
// Final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]
// Append to the endarrName.push('newName1');
// Prepend to the startarrName.unshift('newName1');
// Insert at index 1arrName.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 1arrName.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 arraysarrName.concat(newAry1, newAry2);//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array
let fruits = ["orange", "banana", "apple", "lemon"]; /* Array declaration */
fruits.push("avacado"); /* Adding an element to the array */
/* Displaying elements of the array */
for(var i=0; i < fruits.length; i++){console.log(fruits[i]);}