JavaScript的关于数组的10种简化方法,必须掌握!

in 读书学习 with 0 comment
  1. filter()

    const words = ['HTML', 'CSS', 'JavaScript', 'Python', 'Java'];

    const longWords = words.filter(word => word.length > 4);

    console.log(longWords); // ["JavaScript", "Python"]

  2. forEach()

    const words = ['HTML', 'CSS', 'JavaScript'];

    words.forEach(word => console.log(word));

    // HTML // CSS // JavaScript

  3. some()

    const myArray = [1, 2, 3, 4, 5];

    const evenExists = myArray.some(element => element % 2 === 0);

    console.log(evenExists); // true

  4. every()

    const myArray = [1, 2, 3, 4, 5];

    const allEven = myArray.every(element => element % 2 === 0);

    console.log(allEven); // false

  5. includes()

    const numbers = [1, 2, 3, 4, 5];

    console.log(numbers.includes(2)); // true

    console.log(numbers.includes(8)); // false

  6. map()

    const numbers = [1, 2, 3, 4, 5];

    const doubled = numbers.map(x => x * 2);

    console.log(doubled);

  7. reduce()

    const numbers = [10, 20, 30, 40];

    const sum = numbers.reduce((x, y) => x + y, 0);

    console.log(sum); // 100

  8. sort()

    const techs = ['HTML', 'CSS', 'JavaScript']; techs.sort(); console.log(techs); // ["CSS", "HTML", "JavaScript"]

    const numbers = [1, 30, 4, 21, 100000]; numbers.sort((x, y) => x - y); console.log(numbers); // [1, 4, 21, 30, 100000]

  9. find()

    const numbers = [7, 14, 8, 128, 56];

    const found = numbers.find(element => element > 10);

    console.log(found); // 14

  10. findIndex()

    const numbers = [5, 12, 8, 130, 44];

    const indexFound = numbers.findIndex(element => element > 15);

    console.log(indexFound); // 3