Array Cardio Day 2


Posted by wayne201299 on 2023-09-25

JavaScript中的陣列運算,some、every、find、findIndex、splice、slice

    const people = [
      { name: 'Wes', year: 1988 },
      { name: 'Kait', year: 1986 },
      { name: 'Irv', year: 1970 },
      { name: 'Lux', year: 2015 }
    ];

    const comments = [
      { text: 'Love this!', id: 523423 },
      { text: 'Super good', id: 823423 },
      { text: 'You are the best', id: 2039842 },
      { text: 'Ramen is my fav food ever', id: 123523 },
      { text: 'Nice Nice Nice!', id: 542328 }
    ];

some

    // Some and Every Checks
    // Array.prototype.some() // is at least one person 19 or older?
    const isAdult = people.some(person => {
      const age = new Date().getFullYear() - person.year
      return age >= 19
    })

every

    // Array.prototype.every() // is everyone 19 or older?
    const allAdult = people.every(person => {
      const age = new Date().getFullYear() - person.year
      return age >= 19
    })

find

    // 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 comment = comments.find(comment => comment.id === 823423)

findIndex

    // Array.prototype.findIndex()
    // Find the comment with this ID
    const commentIndex = comments.findIndex(comment => comment.id === 823423)

splice

    // delete the comment with the ID of 823423
    comments.splice(commentIndex, 1)

slice

slice可以在不影響原始操作的陣列情況下對陣列做修改

    // delete the comment with the ID of 823423
    const newComments = [
        ...comments.slice(0, commentIndex), 
        ...comments.slice(commentIndex + 1)
    ]

#javascript







Related Posts

Callback function 用法補充

Callback function 用法補充

[BE101] 資訊安全

[BE101] 資訊安全

初識 shell script

初識 shell script


Comments