🔥5min读懂JavaScript数组!学不会你找渣渣辉来坎我!🔥

86 阅读5分钟

什么是数组?

数组是一种基本的数据结构,在JavaScript中它可以被灵活的声明,可以长度不定,内部可以储存各种各样的数据类型,甚至能够嵌套数组和对象:

const arr = [1, 2, [3, 4], 5, { name: 'Skye', age: 18 }, null, undefined, "Array!", true]
console.log(arr); // [1, 2, [3, 4], 5, { name: 'Skye', age: 18 }, null, undefined, "Array!", true]

数组中的每个数据项称为“元素”,在JS中所有元素的类型可以不同。数组中的元素可以通过索引(通常是数字)来访问。

用途:用于存储一系列同类型的数据,便于批量处理。

如何声明一个数组?

  1. 数组字面量

    const arr = [];
    
  2. new Array()

    new Array在参数数量不同的时候有不同的行为:

    const arr1 = new Array(); // 没有参数时,创建一个空数组,长度为0
    const arr2 = new Array(5); // 有1个参数时,创建一个长度为参数的数组,值初始化为 undefined
    const arr3 = new Array(1,2,3,true,[1,2,3],'Fade')
    // 有多个参数时,让这些参数成为数组中的元素
    
  3. Array of()

    Array of() 用于创建一个具有任意数量参数的新数组实例。也就是传入的值无论数量多少,都会成为数组的元素

    const arr1 = Array of(1);
    const arr2 = Array of(2,false,'Kay/O')
    

数组的各种方法

Array.fill()

这个方法通常被用来初始化数组,利用这个方法,可以用参数填充数组。

array.fill(value, start, end)
// value 为必填变量
// start 和 end 分别对应开始填充的索引和结束填充的索引(但不包括这个索引), 
// start 和 end 非必填
const arr = new Array(10).fill(8);// 新建一个长度为10的数组,所有元素值均为8
const arr2 = new Array(14).fill('Skye'); //新建一个长度为14的数组,所有元素值均初始化为'Skye'

Array.push()

其可以向数组的末尾添加一个或多个元素,并返回新的数组长度

  • 语法array.push(element1, ..., elementN)
   let arr = [1, 2, 3];
   let newLength = arr.push(4, 5);
   console.log(arr); //  [1, 2, 3, 4, 5]
   console.log(newLength); // 5

Array.pop()

删除数组的最后一个元素,并返回该元素

  • 语法array.pop()
   let arr = [1, 2, 3];
   let lastElement = arr.pop();
   console.log(arr); // [1, 2]
   console.log(lastElement); //  3

Array.unshift()

数组的开头添加一个或多个元素,并返回新的数组长度

  • 语法array.unshift(element1, ..., elementN)
    let arr = [2, 3, 4];
    let newLength = arr.unshift(1);
    console.log(arr); // [1, 2, 3, 4]

Array.shift()

删除数组的第一个元素,并返回该元素

  • 语法array.shift()
    let arr = [1, 2, 3];
    let firstElement = arr.shift();
    console.log(arr); // [2, 3]
    console.log(firstElement) // 1

Array.splice()

从数组中添加/删除元素,并返回被删除的元素组成的数组

  • 语法array.splice(start, deleteCount, item1, ..., itemN)

  • 参数

    • start:开始修改的位置(从0开始计数)。
    • deleteCount:要删除的元素个数。如果为0,则不删除任何元素。
    • item1, ..., itemN:要插入到数组中的新元素。
   let arr = [1, 2, 3, 4];
   let removed = arr.splice(1, 2); // 从位置1开始删除2个元素
   console.log(arr); // 输出: [1, 4]
   console.log(removed); // 输出: [2, 3]
   arr = [1, 2, 3, 4];
   arr.splice(1, 0, 'a', 'b'); // 从位置1开始插入'a'和'b'
   console.log(arr); // 输出: [1, 'a', 'b', 2, 3, 4]

Array.slice()

返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括 end)。

  • 语法array.slice(begin, end)

  • 参数

    • begin:开始提取的位置(从0开始计数)。如果省略,则从索引0开始。
    • end:结束提取的位置(但不包含)。如果省略,则一直提取到数组的末尾。
   let arr = [1, 2, 3, 4, 5];
   let newArr = arr.slice(1, 3); // 提取从位置1到位置3(不包括3)的元素
   console.log(newArr); // 输出: [2, 3]

Array.forEach()

对数组中的每个元素执行一次提供的函数。它并没有返回值,如果硬要返回,那么值会是undefined。

  • 语法array.forEach(callback(currentValue, index, array), thisArg)

  • 参数

    • callback:为数组中每个元素执行的函数。

      • currentValue:当前元素的值。
      • index:当前元素的索引。
      • array:调用 forEach 的数组。
    • thisArg:可选参数,用作 callback 函数中的 this 值。

    let arr = [1, 2, 3];
    arr.forEach((value, index) => {
        console.log(`Index ${index}: Value ${value}`);
    });
    // 输出:
    // Index 0: Value 1
    // Index 1: Value 2
    // Index 2: Value 3

Array.map()

返回一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后的返回值

  • 语法array.map(callback(currentValue, index, array), thisArg)

  • 参数

    • callback:为数组中每个元素执行的函数。

      • currentValue:当前元素的值。
      • index:当前元素的索引。
      • array:调用 map 的数组。
    • thisArg:可选参数,用作 callback 函数中的 this 值。

    let arr = [1, 2, 3];
    let newArr = arr.map(x => x * 2);
    console.log(newArr); // 输出: [2, 4, 6]

Array.filter()

  • 功能:创建一个新数组,其中包含所有通过测试的元素

  • 语法array.filter(callback(element, index, array), thisArg)

  • 参数

    • callback:为数组中每个元素执行的函数。

      • element:当前元素的值。
      • index:当前元素的索引。
      • array:调用 filter 的数组。
    • thisArg:可选参数,用作 callback 函数中的 this 值。

    let arr = [1, 2, 3, 4, 5];
    let filteredArr = arr.filter(x => x % 2 === 0);
    console.log(filteredArr); // 输出: [2, 4]

由于Array.filter()主要通过回调函数进行筛选合适的元素,合适的元素会被加入到新的数组并返回,所以我们传入的回调函数的返回值应该是个布尔值,返回true或者false,不然这个回调函数就没有意义了。

如果我们的回调函数的返回值不是true或者false,则会被自动转换:

  • false0"" (空字符串), nullundefinedNaN 被转换为 false
  • 其他所有值(包括非零数字、非空字符串、对象、数组等)被转换为 true

Array.reduce()

  • 功能:对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

  • 语法array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)

  • 参数

    • callback:为数组中每个元素执行的函数。

      • accumulator:累加器累计回调的返回值。
      • currentValue:当前元素的值。
      • currentIndex:当前元素的索引。
      • array:调用 reduce 的数组。
    • initialValue:作为第一次调用 callback 函数时的第一个参数的值。如果没有提供初始值,则将使用数组的第一个元素作为初始值。

   let arr = [1, 2, 3, 4];
   let sum = arr.reduce((acc, curr) => acc + curr, 0);
   console.log(sum); // 输出: 10