Home > Article > Web Front-end > How to add, delete, modify and check arrays in JavaScript
This article shares the common operation methods of arrays in JavaScript. It has certain reference value. I hope it will be helpful to everyone.
Arrays are an important knowledge point in JavaScript. How to operate them It is even more difficult. Today I will share with you several commonly used operating methods in arrays. These methods can change the number, order, etc. of arrays and can be applied to actual cases to greatly reduce the complexity of the program.
Code
<script type="text/javascript"> var arr=[1,2]; </script>
push() method
push refers to adding data to the last digit of the array. You can add one, Or multiple
pop () method
pop refers to the When cutting out the last digit, you need to pay attention to the fact that you cannot pass parameters in the pop() brackets, and it will be invalid if you write it.
unshift() and shift() methods
unshift () adds content from the first position, shift() subtracts content from the first position
## sort () method
to the array Sort from small to large, sorted by asc code
##reverse () method
Arrange the array in reverse order
##splice ()Method
refers to starting from which number, how much length to intercept, passing parameters and adding new data at the interception point
1. If two parameters are filled in splice, it means starting from this bit and how many bits will be intercepted.
Example: arr.slice(1,2) starts from the first digit and intercepts to the second digit2. If only one parameter is filled in splice, it means from which digit Start intercepting and continue intercepting until the end. Example: arr.slice(1) intercepts from the first digit to the last digitjoin () method
The string form needs to be used in the brackets, so that the arrays will be connected with the added things
The form of the string must be in the standard format
##Case sharing
Use push and sort methods to deduplicate arrays and arrange them in order
Program ideas
: Create first Create a new empty array to store the new value, and then use a for loop to traverse the array. Use whether indexof is equal to -1 to determine whether the array already exists in the new array. If not, put it into the new array, and finally output the sorting Code
<script> var arr=[1,1,1,3,5,4,6,5,4,3,2,6,4,7,8,7]; var newArr=[]; //新建一个空数组 for (var i = 0; i < arr.length; i++) { if(newArr.indexOf(arr[i])==-1){//判断是否存在newArr中,不存在就放到里面 newArr.push(arr[i]); } } newArr.sort();//将数组按顺序排列输出 console.log(newArr); </script>
Result
Summary: The above is the entire content of this article. I hope it will be helpful to everyone in learning arrays.
The above is the detailed content of How to add, delete, modify and check arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!