总结
filter(筛选条件为true的项)
map(你想要输出的东西),进来多少个 出去多少个
sort(),默认可排字母顺序。sort(compareFn(a, b))其中compareFn(a, b)返回的值若大于0则a在b的后面。
reduce(),最复杂。reduce(func(){上一轮计算出的结果值,当前值},初值
)
console.table()可以将对象数组以表格形式列出来。
const eighty = people. filter ( person =>
( person. bornYear>= 1980 && person. bornYear< 1989 ) )
console. table ( eighty) ;
const mapRes = people. map ( person =>
` ${ person. firstName} ${ person. lastName} `
)
console. log ( mapRes) ;
const ordered = people. sort ( ( a, b ) => {
if ( a. bornYear> b. bornYear) {
return 1
} else { return - 1 }
} )
const order2 = people. sort ( ( a, b ) => {
return a. bornYear- b. bornYear
} )
const order3 = people. sort ( ( a, b ) => a. bornYear > b. bornYear ? - 1 : 1 )
console. table ( order3) ;
const totalYear = people. reduce ( ( all, person ) => {
return all+= person. pastedYear- person. bornYear
} , 0 )
console. log ( totalYear) ;
const orderLived = people. sort ( ( a, b ) => {
const aLive = a. pastedYear- a. bornYear;
const bLive = b. pastedYear- b. bornYear;
if ( aLive> bLive) {
return 1
} else { return - 1 }
} )
console. table ( orderLived)
footer = [ 'About' , 'Blog' , 'Careers' , 'Advertise with us' , 'Product help' , 'Report an issue' , 'MDN Community' , 'MDN Forum' , 'MDN Chat' , 'Web Technologies' , 'Learn Web Development' , 'MDN Plus' , 'Hacks Blog' ]
footer2 = footer. filter ( foot => foot. includes ( 'b' ) )
console. log ( footer2) ;
const alpha = names. sort ( )
console. log ( alpha) ;
const alpha2 = names. sort ( ( a, b ) => {
const [ a1, a2] = a. split ( ' ' )
const [ b1, b2] = b. split ( ' ' ) ;
return a2> b2? 1 : - 1 ;
} )
console. log ( alpha2) ;
const animals = [ 'cat' , 'dog' , 'cat' , 'elephant' , 'lion' , 'dog' , 'tiger' , 'elephant' , 'panda' , 'cat' , 'panda' , 'lion' , 'tiger' , 'dog' , 'elephant' , 'lion' , 'panda' , 'cat' , 'tiger' , 'panda' ] ;
const count = animals. reduce ( ( obj, item ) => {
if ( ! obj[ item] ) {
obj[ item] = 0
}
obj[ item] ++
return obj;
} , { } )
console. log ( count) ;