【js30天挑战】第四天:数组操作

总结

filter(筛选条件为true的项)

map(你想要输出的东西),进来多少个 出去多少个

sort(),默认可排字母顺序。sort(compareFn(a, b))其中compareFn(a, b)返回的值若大于0则a在b的后面。

reduce(),最复杂。reduce(func(){上一轮计算出的结果值,当前值},初值)

console.table()可以将对象数组以表格形式列出来。

//1. filter
  const eighty = people.filter(person=>
    (person.bornYear>=1980 && person.bornYear<1989))
    //会筛选true的条件

  console.table(eighty);//new

//2. map 进来多少个 出去多少个
  const mapRes = people.map(person=>
    // 这样写不对,因为map里面是你的新数组里想要什么东西,而不是操作
    // delete person.location
    // delete person.bornYear
    // delete person.pastedYear
    `${person.firstName} ${person.lastName}`
  )
  console.log(mapRes);

//3. sort
//逻辑是compareFn(a, b)返回的值若大于0则a在b的后面。
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);

// 4. reduce 
//有点mapreduce里面reduce的意思
//题目:计算这些人一共活了多少岁
//const sumWithInitial = array1.reduce(
//     (accumulator, currentValue) => accumulator + currentValue,
//   initialValue
// );

const totalYear = people.reduce((all,person)=>{
    return all+=person.pastedYear-person.bornYear
},0)
console.log(totalYear);

//5. 按生命长度排序
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)

//6. filter复习:筛选含有b字母的单词
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);

//7. 按字母表顺序排序人名
//按名排序
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);


//8. reduce练习:统计个数
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);

【js30天挑战】第四天:数组操作_第1张图片

你可能感兴趣的:(javascript,前端,vue.js)