javaScript数组常用方法

153 阅读2分钟

JavaScript 中的数组是内置的、有序的数据集合,提供了许多用于操作数组的方法。以下是一些常用的数组方法:

  1. map()

    • 创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后的返回值。
    const numbers = [1, 2, 3, 4];
    const squares = numbers.map(x => x * x);
    
  2. filter()

    • 创建一个新数组,包含通过所提供函数实现的测试的所有元素。
    const numbers = [1, 2, 3, 4];
    const evenNumbers = numbers.filter(x => x % 2 === 0);
    
  3. reduce()

    • 对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
    const numbers = [1, 2, 3, 4];
    const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
    
  4. forEach()

    • 遍历数组中的每个元素,对每个元素执行一个提供的函数,没有返回值。
    const numbers = [1, 2, 3, 4];
    numbers.forEach(x => console.log(x));
    
  5. find()

    • 返回数组中满足提供的测试函数的第一个元素的值,否则返回undefined。
    const numbers = [1, 2, 3, 4];
    const found = numbers.find(x => x > 2);
    
  6. some()

    • 测试数组中是不是至少有一个元素通过了被提供的函数测试,如果是返回true,否则false。
    const numbers = [1, 2, 3, 4];
    const hasOne = numbers.some(x => x > 2);
    
  7. every()

    • 测试数组的所有元素是否都通过了被提供的函数测试,如果是返回true,否则false。
    const numbers = [1, 2, 3, 4];
    const allArePositive = numbers.every(x => x > 0);
    
  8. slice()

    • 返回一个新数组,包含从开始到结束(不包括结束)选择的数组的一部分。
    const numbers = [1, 2, 3, 4];
    const part = numbers.slice(1, 3);
    
  9. splice()

    • 用于添加/删除数组的元素。
    const numbers = [1, 2, 3, 4];
    numbers.splice(1, 1, 'a');
    
  10. concat()

    • 用于合并两个或多个数组。
    const numbers1 = [1, 2, 3];
    const numbers2 = [4, 5, 6];
    const combined = numbers1.concat(numbers2);
    
  11. push()

    • 将一个或多个元素添加到数组的末尾,并返回新数组的长度。
    const numbers = [1, 2, 3];
    numbers.push(4);
    
  12. pop()

    • 从数组中删除最后一个元素,并返回被删除的元素。
    const numbers = [1, 2, 3];
    const last = numbers.pop();
    
  13. shift()

    • 从数组中删除第一个元素,并返回被删除的元素。
    const numbers = [1, 2, 3];
    const first = numbers.shift();
    
  14. unshift()

    • 向数组的开头添加一个或更多元素,并返回新数组的长度。
    const numbers = [1, 2, 3];
    numbers.unshift(0);
    
  15. includes()

    • 用于检查数组是否包含某个元素,根据情况返回truefalse
    const numbers = [1, 2, 3, 4];
    const hasThree = numbers.includes(3);
    
  16. flat()

    • 将数组中的所有元素与遍历到的子数组中的元素合并为一个新数组。
    const numbers = [1, 2, [3, 4]];
    const flatNumbers = numbers.flat();
    
  17. flatMap()

    • 首先使用映射函数映射每个元素,然后将结果展平。
    const numbers = [1, 2, 3, 4];
    const flatMapped = numbers.flatMap(x => [x, x * 2]);
    

这些方法覆盖了从数组的创建、转换、搜索、添加和删除等常见操作。掌握这些方法可以大大提高处理数组的效率。