This article and everyone to share is mainly in JavaScript on the array of the most important 5 methods, take a look at it, hope that you learn JavaScript help.
Array.foreach ()
The . ForEach () method makes it easy for you to iterate through each element in the array , and you can manipulate each element in the callback function. The . ForEach () method does not return a value, and you do not need to write the return in the callback function, which is meaningless.
var animals = [' dog ', ' cat ', ' mouse '];
Animals. ForEach (function(item) {
Console.log (item);
});
Array.map ()
The . Map () method can traverse the entire array and then return a new array in which the elements in the new array have been processed by the specified callback function.
If you want to modify each element in the array and then save the modified array to a new array, it is most convenient to use the. Map () method.
var numbers = [2, 4, 6, 8];
var doublenums = Numbers.map (function(element) {
return element * 2;
});
Console.log (' doublenums: ', doublenums)
Array.filter ()
The . Filter () method filters out certain elements in the array , and you can set the conditions in the callback function, excluding the elements that do not match the criteria.
var scores = [3, 12, 5, 23, 19, 7];
var topscores = Scores.filter (function(item) {
if (Item > 10) {
return true;
} Else {
return false;
}
});
Console.log (' topscores: ', topscores);
Array.indexof ()
indexOf () can tell you where an element is in the array, it returns the index value, and if there are duplicate elements in the array, it returns the position of the first element.
var a = [2, 9, 9, 18];
var i = A.indexof (9);
Console.log (' I: ', i);
/*
if (a.indexof (7) = = =-1) {
This element is not in the array
}*/
Array.every ()
The function of the . Every () method is to check each element in the array with the specified callback function, and if this callback function returns true for each element, then . every () returns True. Otherwise, . Every () returns FALSE.
If you want to know if all the elements in the array meet a certain condition, using. Every () is the most convenient.
var ages = [23, 19, 32, 44];
var olderThan18 = Ages.every (function(element) {
return element > 18;
});
Console.log (' olderThan18: ', olderThan18);
The above 5 methods are just a few of the most important things about arrays in many JavaScript methods, as well as a lot of methods for arrays, toolkits (Lodash and underscore ), etc. are very useful.
Source: Geek Headlines
5 array methods required for efficient JavaScript programming