In the big front-end field, after the front-end separation, the use of the interface to call the data in the case, it is indispensable to the array of processing, today to bring you js array in the most common several processing methods

forEach()

Usage: Used to call each element of the array and pass the element to the callback function.

let ages = [22, 33, 16, 40];
(function myFunction() {
	ages.forEach(function(item,index,array){
		array[index] = item * 2
	})
	console.log(ages) //[44, 66, 32, 80]
})()
Copy the code

map()

Usage: Returns a new array in which the elements are the values of the original array.

let ages = [22, 33, 16, 40];
(function myFunction() {
	let map = ages.map(function(item,index,array){
		return item * 2
	})
	console.log(map)
})()
Copy the code

Differences between map and forEach:

Similarity: They both iterate over each item of a number group and support three parameters: item(each item), index(index value), and array(original array). Use whatever parameters you need.

Difference: Foreach calls each item and passes the value back to the callback function without a return. The map method, after setting conditions, returns a new array.

filter()

Usage: Creates a new array of elements by checking all the elements in the specified array.

Advantage: Does not change the original array.

let ages = [22, 33, 16, 40]; (function myFunction() { const a = ages.filter(function(item){ return item > 25 }); The console. The log (a) / / [40] 33}) ()Copy the code

some()

Usage: Returns a Boolean that checks whether an element in an array meets a specified condition, true if it does, false otherwise.

let ages = [22, 33, 16, 40];
(function myFunction() {
    let isSome = ages.some(function(item,index,array){
	return item > 35
    })
    console.log(isSome) //true
})()	
Copy the code

every()

The usage is very similar to some(), which supports three arguments,

let ages = [22, 33, 16, 40]; (function myFunction() { let isSome = ages.every(function(item,index,array){ return item > 35 }) console.log(isSome) }) ()Copy the code

The difference between some() and every() :

The some () method iterates through the array, returning false if one of the items in the array satisfies the condition that returns true.

The every () method iterates through the array and returns true only when each item in the array satisfies the condition.

The For loop

Last but not least, let is recommended to define a in a for loop. Var will leak memory.

The for loop iterates through the code block multiple times, stopping the loop when the condition is not true.

let ages = [22, 33, 16, 40]; (function myFunction() { for(let a = 0; a < ages.length; a++){ console.log(ages[a]) } })()Copy the code