JavaScript 30天编码挑战——第 7 天

181 阅读3分钟

这是我参与更文挑战的第9天,活动详情查看: 更文挑战

Array Cardio Day 2

一、效果展示

这一部分是第 4 天挑战的续集,依旧是数组的练习,继续熟悉 Array 的一些基本方法,有 some()、every()、find()、splice()、slice()。

文档提供了可用于操作的 people 和 comments 数组,模拟的是人员信息及评论数据,基于这两个数组练习数组的的各个方法,打开 HTML 文件后在 Console 面板中查看输出结果。

练习效果

image.png

二、实现

最终代码

三、总结回顾

主要都是针对两个数组的练习操作,拒绝花里胡哨,进入正题,那么我们要根据两个数组去做哪些练习呢?

针对 people 数组:

  1. 是否有人超过 19 岁?
  2. 是否所有人都是成年人?

针对 comments 数组:

  1. 找到 ID 号为 823423 的评论
  2. 删除 ID 号为 823423 的评论

    • 获取此 ID 对应元素在数组中所处的位置
    • 利用位置,删除该子元素
    • 或者拼接新的数组

过程分解

1.针对 people 数组

(1) 是否有人超过 19 岁?

// Array.prototype.some() // is at least one person 19 or older?
    const ans = people.some(p =>{
      return new Date().getUTCFullYear() - p.year >= 19
    })
    console.log(ans);   // true

(2) 是否所有人都是成年人?

// Array.prototype.every() // is everyone 19 or older?
    const ans1 = people.every(p =>{
      return new Date().getUTCFullYear() - p.year >= 19
    })
    console.log(ans1);   // false
  1. 针对 comments 数组

(1)找到 ID 号为 823423 的评论

    // Array.prototype.find()
    // Find is like filter, but instead returns just the one you are looking for
    // find the comment with the ID of 823423

    const ans2 = comments.find( comment => comment.id === 823423);

    console.log(ans2);  // {text: "Super good", id: 823423}

注意里边的这个提示信息:

Find is like filter, but instead returns just the one you are looking for

(2)删除 ID 号为 823423 的评论

    ①获取此 ID 对应元素在数组中所处的位置

    // Array.prototype.findIndex()
    // Find the comment with this ID

    const ans3 = comments.findIndex( comment => comment.id === 823423);

    console.log(ans3);   // 1

    ②利用位置,删除该子元素

// delete the comment with the ID of 823423
    
    //slice,splice
    
    comments.splice(ans3,1);

    console.log(comments);      //  [{ text: 'Love this!', id: 523423 },{ text: 'You are the best', id: 2039842 },{ text: 'Ramen is my fav food ever', id: 123523 },{ text: 'Nice Nice Nice!', id: 542328 }]

    ③或者拼接新的数组

// delete the comment with the ID of 823423
    
    //slice,splice

    const ans4 = comments.slice( 0, ans3);
    const ans5 = comments.slice(ans3 + 1);

    console.log(ans4,ans5,comments);

image.png 这时候我们发现,我们的数组被分成了两段,我们将两段数组进行合并:

const ans4 = comments.slice( 0, ans3);
    const ans5 = comments.slice(ans3 + 1);

    const ans6 = [...ans4,...ans5];

    console.log(ans6,comments);

image.png

四、重难点

some() 和 every()

every()与some()方法都是JS中数组的迭代方法。

  • every()是对数组中每一项运行给定函数,如果该函数对每一项返回true,则返回true。
  • some()是对数组中每一项运行给定函数,如果该函数对任一项返回true,则返回true。

不同之处在于,some 一直在找符合条件的值,一旦找到,则不会继续迭代下去。every 从迭代开始,一旦有一个不符合条件,则不会继续迭代下去。

注意: every() 不会对空数组进行检测。

find 和 fineIndex()

ES6为Array增加了find(),findIndex函数。

  • find()函数用来查找目标元素,找到就返回该元素,找不到返回undefined,
  • findIndex()函数也是查找目标元素,找到就返回元素的位置,找不到就返回-1。

slice 和 splice

关于这两个的区别,我看到有人已经总结的非常全面了,我这里就借花献佛了,大家一起学习。

地址:blog.csdn.net/xiaoqingpan…

这里有一个值得注意的地方:

slice() 方法不会改变原数组,而是返回一个子数组,如果想删除数组中的一段元素,应该使用Array.splice()方法。


今天的练习就到此结束了