3 methods: 1. Use unshift() to insert an element at the beginning, the syntax is "array object.unshift(element)"; 2. Use push() to insert an element at the end, the syntax "Array object.push(element)"; 3. Use concat(), the syntax is ""array.concat(element)".
The operating environment of this tutorial :windows7 system, ECMAScript version 6, Dell G3 computer.
es6 Three ways to add an element to an array
1 , Use the unshift() function
The unshift() function can insert elements at the beginning of the array. This function can append one or more parameter values to the head of the array:
array.unshift(元素1, 元素2, ..., 元素X)
The first parameter Element1
is the new element 0 of the array, the second parameter Element2
is the new element 1, and so on, and finally returns the length of the array after adding the element.
Let’s take a closer look at the following example:
var a = [0]; //定义数组 console.log(a); //返回[0] a.unshift(1); //增加1个元素 console.log(a); //返回[1,0]
2. Use the push() function
## The #push() method can append one or more parameter values to the end of the array and return the length of the array after adding elements.array.push(元素1, 元素2, ..., 元素X)
var a = [0]; //定义数组 console.log(a); //返回[0] a.push(2); //增加1个元素 console.log(a); //返回[0,2]
3. Use the concat() function
The concat() method can connect two or more arrays and will use one or more arrays as parameters. Elements of multiple arrays are added to the end of the specified array.You can also insert one or more given elements, and all the parameters passed can be added to the end of the array in order.
var a = [1,2,3,4,5]; //定义数组 console.log(a); var b = a.concat(6); //为数组a连接1个元素 console.log(b);
##Explanation: The concat() method will create and return a new array instead of adding new elements to the original one; but unshift The () method will add elements based on the original array.
[Related recommendations:
javascript video tutorialThe above is the detailed content of How to add an element to an array in es6. For more information, please follow other related articles on the PHP Chinese website!