likes
comments
collection
share

[Javascript 进阶]-数组

作者站长头像
站长
· 阅读数 14

生成数组

Array()

// Array(arrayLength), 0 <= arrayLength <= 2^32 - 1
// 生成长度为arrayLength的空数组,其中的每一项为undefined
const arr = new Array(4);
console.log(arr);
console.log(arr[0]);
// [,,,]
// undefined

// Array(element0,element1,...elementN)
// 生成由括号内组成的数组
const arr = new Array('a', 'b', 3, '4', true);
// ["a","b",3,"4",true]

Array.from()

接受两个参数,第一个参数是可迭代的对象,第二个参数是一个函数,用于对每一个迭代对象进行操作 可迭代的对象包含

  1. 数组
  2. 类数组
  3. 字符串
  4. Set
  5. Map
// 1. 数组
const arr = Array.from([1,2,3])
// [1,2,3]

// 2. 类数组
const imageElements = document.querySelectorAll('img');
const imageSrcs = Array.from(imageElements, (image) => image.src);

// 3. 字符串
const arr = Array.from('array');
// ["a","r","r","a","y"]

// 4. Set
const set = new Set(["foo", "bar", "baz", "foo"]);
Array.from(set);
// [ "foo", "bar", "baz" ]

// 5. Map
const map = new Map([
  [1, 2],
  [2, 4],
  [4, 8],
]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]

Array.of()

// Array.of(ele0,ele1,...,eleN),生成括号内元素对应的数组
const arr = Array.of('a', 'b', 3, '4', true);
// ["a","b",3,"4",true]

判断是否是数组

const arr = Array.of('a', 'b', 3, '4', true);
console.log(arr instanceof Array) // true
console.log(Array.isArray(arr)) // true

操作数组,返回新数组,不对原有数组产生影响

Array.prototype.forEach((element, index, thisArray) => void)

对数组的每个元素执行一次给定的函数

const array1 = ['a', 'b', 'c'];

array1.forEach((element) => console.log(element));

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

Array.prototype.map((element, index, thisArray) => element)

传入参数为一个函数,对数组进行遍历,每次遍历可以使用函数将数组的每个元素进行修改

const users = [{
    name: 'user1',
    isVip: true,
    title: '一般用户'
    }, {
    name: 'user1',
    isVip: true,
    title: '一般用户'
    }, {
    name: 'user1',
    isVip: false,
    title: '一般用户'
    }];
const newUsers = users.map((user) => {
    if (user.isVip) {
        return {
            ...user,
            title: 'Vip用户'
        }
    }
    
    return user;
});
/*
    [{
      "name": "user1",
      "isVip": true,
      "title": "Vip用户"
    },
    {
      "name": "user2",
      "isVip": true,
      "title": "Vip用户"
    },
    {
      "name": "user3",
      "isVip": false,
      "title": "一般用户"
    }] 
*/

Array.prototype.filter((element, index, thisArray) => Boolean)

使用传入函数对已有数组进行筛选操作,返回结果为true的元素

const users = [{
    name: 'user1',
    isVip: true,
    title: '一般用户'
    }, {
    name: 'user2',
    isVip: true,
    title: '一般用户'
    }, {
    name: 'user3',
    isVip: false,
    title: '一般用户'
    }];
const newUsers = users.fillter((user) => user.isVip);
/*
    [
        {
          "name": "user1",
          "isVip": true,
          "title": "一般用户"
        },
        {
          "name": "user2",
          "isVip": true,
          "title": "一般用户"
        }
    ] 
*/

Array.prototype.flat(depth)

创建一个新的数组,并根据指定深度递归地将所有子数组元素拼接到新的数组中

const arr1 = [0, 1, 2, [3, 4]];
arr1.flat();
// [0,1,2,3,4]
const arr2 = [0, 1, [2, [3, [4, 5]]]];
arr2.flat();
// [0, 1, 2, [3, [4, 5]]]
arr2.flat(2);
// [0, 1, 2, 3, [4, 5]]
arr2.flat(Infinity);
// [0, 1, 2, 3, 4, 5]

Array.prototype.concat(element1,element2,...elementN)

合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

// 传入单个数组
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
// array3 => ["a", "b", "c", "d", "e", "f"]

// 传入多个数组
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
const numbers = num1.concat(num2, num3);
// numbers => [1, 2, 3, 4, 5, 6, 7, 8, 9]

// 传入组合
const letters = ["a", "b", "c"];
const alphaNumeric = letters.concat(1, [2, 3]);
// alphaNumeric => ['a', 'b', 'c', 1, 2, 3]

// concat是浅拷贝,所以会保留引用
const num1 = [[1]];
const num2 = [2, [3]];

const numbers = num1.concat(num2);
// numbers => [[1], 2, [3]]

// 修改 num1 的第一个元素
num1[0].push(4);
// numbers => [[1, 4], 2, [3]]

Array.prototype.slice(startIndex, endIndex)

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
// 只写起始位置,会从起始位置截断至最后
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

// 写上起始和结束位置
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

// 位置为负数,会从后往前计算
console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

// 这样就能够获取正数和倒数之间的数据
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

数组的查找

Array.prototype.at(index)

返回该索引对应的元素,允许正数和负数。负整数从数组中的最后一个元素开始倒数。

const array1 = [5, 12, 8, 130, 44];
array1.at(2) // 8
array1.at(-2) // 130

Array.prototype.includes(element, startIndex)

判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
// Expected output: false

// startIndex 可以控制查找的起始位置,若超出数组长度直接返回false
console.log(pets.includes('cat', 1));
// Expected output: false
// 如果 `fromIndex` 为负值,计算出的索引将作为开始搜索 `searchElement` 的位置。如果计算出的索引小于 `0`,则整个数组都会被搜索。

const arr = ["a", "b", "c"];
// 数组长度为 3
// fromIndex 为 -100
// 计算出的索引为 3 + (-100) = -97

arr.includes("a", -100); // true
arr.includes("b", -100); // true
arr.includes("c", -100); // true
arr.includes("a", -2); // false

Array.prototype.indexOf(searchElement, startIndex)

返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。

// 找出指定元素出现的所有位置
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.indexOf(element);
while (idx !== -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]

find 系列

Array.prototype.find((element, index, thisArray) => Boolean)

返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

const inventory = [
  { name: "apples", quantity: 2 },
  { name: "bananas", quantity: 0 },
  { name: "cherries", quantity: 5 },
];

function isCherries(fruit) {
  return fruit.name === "cherries";
}

console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }

Array.prototype.findIndex((element, index, thisArray) => Boolean)

返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。

function isPrime(element) {
  if (element % 2 === 0 || element < 2) {
    return false;
  }
  for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
    if (element % factor === 0) {
      return false;
    }
  }
  return true;
}

console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1,没有找到
console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2(array[2] 是 7)

Array.prototype.findLast((element, index, thisArray) => Boolean)

反向迭代数组,并返回满足提供的测试函数的第一个元素的值。如果没有找到对应元素,则返回 undefined。

const array1 = [5, 12, 50, 130, 44];

const found = array1.findLast((element) => element > 45);

console.log(found);
// Expected output: 130

Array.prototype.findLastIndex((element, index, thisArray) => Boolean)

反向迭代数组,并返回满足所提供的测试函数的第一个元素的索引。若没有找到对应元素,则返回 -1。

const array1 = [5, 12, 50, 130, 44];

const isLargeNumber = (element) => element > 45;

console.log(array1.findLastIndex(isLargeNumber));
// Expected output: 3
// Index of element with value: 130

检测数组是否通过某条件

Array.prototype.every((element, index, thisArray) => Boolean)

测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值

function isBiggerThan10(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBiggerThan10); // false
[12, 54, 18, 130, 44].every(isBiggerThan10); // true

Array.prototype.some((element, index, thisArray) => Boolean)

测试数组中是否至少有一个元素通过了由提供的函数实现的测试。如果在数组中找到一个元素使得提供的函数返回 true,则返回 true;否则返回 false。

function isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

堆栈操作

Array.prototype.shift()

从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// Expected output: Array [2, 3]

console.log(firstElement);
// Expected output: 1

Array.prototype.unshift(element1, element2, ..., elementN)

将指定元素添加到数组的开头,并返回数组的新长度

array1.unshift(4, 5)
console.log(array1);
// Expected output: Array [4, 5, 2, 3]

队列操作

Array.prototype.push(element0, element1, ..., elementN)

将指定的元素添加到数组的末尾,并返回新的数组长度。

const plants = ['broccoli'];
['cauliflower', 'cabbage', 'kale', 'tomato'].forEach(item => plants.push(item));

console.log(plants);
// ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

Array.prototype.pop()

从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度。

plants.pop();
console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

累计操作 Array.prototype.reduce((prevValue, currentValue, index, thisArray) => calculatedElement, initValue)

对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被用作初始值,迭代器将从第二个元素开始执行(即从索引为 1 而不是 0 的位置开始)。

// 累加
const sum = [1, 2, 3, 4].reduce((prev, current) => prev + current);
// sum => 10

// n的阶乘
const genNArray = n => Array.from(Array(n), (_, index) => index + 1);
const nArray = genNArray(5);
const mult = nArray.reduce((prev, current) => prev * current);
// mult => 120

// 求最大(最小
const getMax = (a, b) => Math.max(a, b);
const getMin = (a, b) => Math.min(a, b);
[1, 100].reduce(getMax); // 100
[1, 100].reduce(getMin); // 1

// 使用 reduce() 来替代 [].filter().map()
// 使用 filter() 和 map() 会遍历数组两次,但是你可以使用 reduce() 只遍历一次并实现相同的效果,从而更高效。
const numbers = [-5, 6, 2, 0];

const doubledPositiveNumbers = numbers.reduce((accumulator, currentValue) => {
  if (currentValue > 0) {
    const doubled = currentValue * 2;
    return [...accumulator, doubled];
  }
  return accumulator;
}, []);

console.log(doubledPositiveNumbers); // [12, 4]

未完待续...

参考文档:

developer.mozilla.org/zh-CN/docs/…