ES6 popular new array syntax, practical application

A .every (value - the current value of the index, index - the index)
basis for judging the condition, whether the elements of the array of all-satisfied, if satisfied then return ture, are not met it returns false

let arr =[2,3,4,5,6,7]
let arr1 = arr.every( (value)=>value<8) 返回true
let arr2 = arr.every( (value)=>value<7) 返回false

Two .some (value - the current value of the index, index - the index)
basis for judging the condition, whether there is a element of the array to meet, if a meet ture is returned, does not meet all returns false

let arr =[2,3,4,5,6,7]
let arr1 = arr.every( (value)=>value>7) 返回false
let arr2 = arr.every( (value)=>value<7) 返回true

Three .filter (value - the current value of the index, index - index)
filter array, a return to meet the requirements of the array

let arr =[2,3,4,5,6,7]
let newarr = arr.filter( (item)=> item<5)
结果 newarr    [2,3,4]

Four .find
find the first qualifying array member

let arr =[2,3,4,5,6,7]
let newarr = arr.find( (item)=>item>3)
结果 newarr    [4]

Five .findIndex
find the index value of the first qualifying array members

let arr =[2,3,4,5,6,7]
let newarr = arr.findIndex( (item)=>item>5)
结果 newarr    [4]

Six .forEach (value - the current value of the index, index - the index, array - the original array)
through the array, no return, to provide the function performed, always returns undefined

let arr =[2,3,4,5,6,7]
let newarr = arr.forEach( (item,index,arr)=>{  }

Seven .includes
number determines whether to include a given value

let arr =[2,3,4,5,6,7]
let newarr = arr.includes(2) 返回true
let newarr = arr.includes(10)返回false

Eight .map
through the array and returns a new array

let arr =[2,3,4,5,6,7]
let newarr = arr.map( (item)=>item*2)
结果 newarr    [4,6,8,10,12,14]

.Reduce nine
accumulators, each value (left to right) were combined in the array, a finally calculated value calculated may be used as shopping cart, the following examples

.reduce( (pre,item)=>{
 return     item.price * item.count + pre
 },0)
 0是pre的值,通常定为0,必须写

It can also be used to re-array

let arr =[2,3,4,5,6,7,7,2]
let newarr = arr.reduce( (pre,item) =>{
if(!pre.includes(item)){
return pre.concat(item)    //concat用于连接两个或多个数组
}else{
return pre
},[])
Released two original articles · won praise 1 · views 36

Guess you like

Origin blog.csdn.net/weixin_45389051/article/details/104632060