The array of JavaScript is a very familiar type and has very powerful functions, but not everyone without front-end learning can master it proficiently. Let’s follow Let’s talk about some methods of arrays
Array deduplication
(1) Give an array arr=[1,2,3 ,3,4], how to remove duplicates?
There is a new data structure Set in es6 var newArr=new Set(arr)
;
var newArr = []; for (var i = 0; i < arr.length; i++) { if(newArr.indexOf(arr[i]) === -1){ newArr.push(arr[i]); } } console.log(newArr); //[1,2,3,4];
foreach executes a given function once for each element in the array, but the original array remains unchanged and has no return value
var arr = [1,2,3,4]; arr.forEach(function(item, index, origin){ item += 1; console.log(item);//2,3,4,5 }) console.log(arr);//[1,2,3,4]
map executes a given function once for each element in the array. The original array remains unchanged and a new array is returned.
var arr = [1,2,3,4]; var newArr=arr.map(function(item, index, origin){ return ++item; }) console.log(newArr);//[2,3,4,5]
filter is to execute a given function once for each element in the array, leaving the original array unchanged and returning a new array that meets the conditions
var arr = [1,2,3,4]; var newArr=arr.filter(function(item, index, origin){ return item>2; }) console.log(newArr);//[3,4]
reduce is that the first parameter is a function. The parameters of this function are the last execution function result pre and the value and index of the current element. It is usually used to find the sum of arrays. The second parameter is The first parameter is the value of pre when the function is executed for the first time. If there is no such parameter, the first value will be regarded as the value of pre
var arr = [1,2,3,4]; var res=arr.reduce(function(pre, cur, curIndex, origin){ console.log(curIndex);//1,2,3 return pre + cur; }) console.log(res);//10 var res=arr.reduce(function(pre, cur, curIndex, origin){ console.log(curIndex);//0,1,2,3 return pre + cur; }, 5) console.log(res);//15
every executes a given function once for each element in the array. If one result is false, false is returned;
var arr = [1,2,3,4]; var res = arr.every(function(item, index, origin){ return item > 2; }) console.log(res);//false
Some is opposite to every, which executes a given function once for each element in the array. If one result is true, it returns true;
var arr = [1,2,3,4]; var res = arr.some(function(item, index, origin){ return item > 2; }) console.log(res);//true
The above is the detailed content of What are the commonly used array functions?. For more information, please follow other related articles on the PHP Chinese website!