I summarize the method array grouped into two categories, one is to change the original array, one is not to change the original array
Here we will introduce the method to change the original array
1.pop () to remove the last element of the array
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); console.log(fruits) //[ 'Banana', 'Orange', 'Apple' ]
2.push () to add elements to the end of the array
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi") 结果输出 Banana,Orange,Apple,Mango,Kiwi
3.reverse () reverse the order of elements in the original array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.reverse(); 输出结果 Mango,Apple,Orange,Banana
4.shift () removes the first element of the array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift() 结果 Orange,Apple,Mango
5.sort () to sort the array elements in the original array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); 输出结果 Apple,Banana,Mango,Orange
6.splice () to insert, delete or replace array elements.
语法 array.splice(index,howmany,item1,.....,itemX)
index pledged to the operation start position array index value, mandatory
howmany represents the number of elements to be deleted must be a number can be zero, if Motian is deleted from the index beginning to the end of the array
item1 .... pledged to add to the new values in the array
var Fruits = [ "Banana", "Orange", "the Apple", "Mango" ]; var newArray = fruits.splice (2 ); the console.log (Fruits) the console.log (newArray) result [ 'Banana', 'Orange' ] [ 'the Apple', 'Mango' ] to change the original returned array is an array of elements in the set are deleted
7.unshift () is inserted into the head elements in the array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon","Pineapple"); fruits 将输出: Lemon,Pineapple,Banana,Orange,Apple,Mango
Above 7 are adding elements push unshift remove elements pop shift in reverse order reverse delete elements splice element sort sort
8.forEach map filter like the case through the array, the original array traversal modified region
It should be noted that modified element value in two situations, when the traversal is a basic element of the data type value is also the case that the value is a reference value of the data element type
Directly to modify the value of the basic data types of the first case will not change the original array, it needs to achieve index changes
let arr = [1,3,5,7,9]; arr.forEach(function(item,index,arr){ arr[index] = 30; }) console.log(arr); //输出 (5) [30, 30, 30, 30, 30]
When the second case
var fruits = [ { name:'aaa', id: 1 }, { name:'bbb', id:2 } ]; fruits.map(item => { if (item.id === 1){ item.name = 'Banana----new' } }) console.log(fruits)