In the previous article, we learned how to use indexes to access elements in array objects. Please see "How js uses indexes to access elements in array objects". This time we will learn how to add elements to an array. You can refer to it if necessary.
In javascript, there are three ways to add elements to an array. Let us look at the first one first.
Let’s look at a small example first.
var arr = new Array(3); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; var newLength = arr.push('four'); console.log(arr);
The result of this small example is
As you can see, in this example, we added an element "## to the end of the array #four”. At the same time, we used the
push method. Let's take a look at this function.
push()The method adds one or more elements to the end of the array and returns the new length.
数组对象.push(要添加到数组的元素)
arrayObject. It
directly modifies arrayObject instead of creating a new array.
var arr = new Array(3); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; var newLength = arr.unshift('four'); console.log(arr);
unshift()The method adds one or more elements to the beginning of the array and returns the new length. Move existing elements sequentially to higher subscripts to make space. The first parameter of the method will become the new element
0 of the array, if there is a second parameter it will become the new element
1, and so on.
unshift() method
does not create a new array , but directly modifies the original array.
var arr = new Array(3); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; var newLength = arr.splice(1,0,'four'); console.log(arr);
splice()The method adds/removes items to/from the array and returns the deleted item.
arrayObject.splice(规定添加/删除项目的位置,要删除的项目数量,向数组添加的新项目)
index and replaces those elements with one or more values declared in the parameter list. The deleted element. If an element is deleted from
arrayObject, an array containing the deleted element is returned.
will directly modify the array.
[Recommended learning:javascript advanced tutorial]
The above is the detailed content of How to add elements to an array in js. For more information, please follow other related articles on the PHP Chinese website!