Add method: 1. Use push() method, syntax "array.push(element 1, element 2,..., element X)"; 2. Use splice() method, syntax "array. splice(arr.length,0,element 1,...,element X)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1, push() method can be Appends one or more elements to the end of the array and returns the new length.
1), syntax:
arrayObject.push(newelement1,newelement2,....,newelementX)
Parameters | Description |
---|---|
newelement1 | Required. The first element to be added to the array. |
newelement2 | Optional. The second element to be added to the array. |
newelementX | Optional. Multiple elements can be added. |
2) Return value:
The new length after adding the specified value to the array .
3) Description:
The push() method can add its parameters to the end of arrayObject in sequence. It directly modifies arrayObject instead of creating a new array.
4), Example:
var arr = new Array(3) arr[0] = "ZhangQian" arr[1] = "LinFang" arr[2] = "HaiKun" console.log(arr);// ["ZhangQian","LinFang","HaiKun"] console.log(arr.push("C"));// 4 console.log(arr);// ["ZhangQian","LinFang","HaiKun","C"] console.log(arr.push("A","B"));// 6 console.log(arr);// ["ZhangQian","LinFang","HaiKun","A","B","C"]
2, The splice() method adds/removes items to/from an array and returns the removed item.
1), syntax:
arrayObject.splice(index,howmany,item1,.....,itemX)
Parameters | Description |
---|---|
index | Required. An integer specifying the position at which to add/remove an item. Use a negative number to specify the position from the end of the array. |
howmany | Required. The number of items to delete. If set to 0, items will not be deleted. |
item1, ..., itemX | Optional. New items added to the array. |
2) Return value:
Type | Description |
---|---|
Array | The new array containing the deleted items, if any. |
3) Description:
The splice() method can be deleted from the index The starting zero or more elements and replaces those removed elements with one or more values declared in the argument list.
If an element is deleted from arrayObject, an array containing the deleted element is returned.
The splice() method will directly modify the array.
4), Example:
var arr = ["A","ZhangQian","LinFang","HaiKun"]; arr.splice(1,0,"B","C"); console.log(arr); arr.splice(arr.length,0,"D","C"); console.log(arr);
javascript advanced tutorial]
The above is the detailed content of What are the ways to add elements to the end of an array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!