1. 数组创建

  • Array.of(...): 创建一个新的数组实例,其中包含传入的所有元素。
点击查看代码
console.log(Array.of(1, 2, 3)); // [1, 2, 3]
console.log(Array.of(7)); // [7]
console.log(Array.of()); // []
  • Array.from(arrayLike, mapFn, thisArg): 从类数组或可迭代对象创建一个新的数组实例。

示例:
从类数组对象创建数组

点击查看代码
const arrayLike = {
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3
};
const arr = Array.from(arrayLike);
console.log(arr); // ['a', 'b', 'c']

从可迭代对象创建数组

点击查看代码
const str = 'hello';
const arr = Array.from(str);
console.log(arr); // ['h', 'e', 'l', 'l', 'o']

使用映射函数

点击查看代码
const numbers = [1, 2, 3, 4];
const doubled = Array.from(numbers, x => x * 2);
console.log(doubled); // [2, 4, 6, 8]

2. 访问和修改

  • length: 返回或设置数组的长度。
    读取长度

** 设置长度:设置 length 属性会改变数组的大小:**

  • at(index): 返回数组中指定位置的元素,负数表示从数组末尾倒数的位置,index是下标索引值。

  • 示例

3. 添加和删除元素

  • push(...elements): 向数组末尾添加一个或多个元素。

  • pop(): 移除并返回数组末尾的元素。

  • unshift(...elements): 向数组开头添加一个或多个元素。

  • shift(): 移除并返回数组开头的元素。

  • splice(start, deleteCount, ...items): 从数组中添加或删除元素。

  • 使用 delete 操作符,删除数组中的指定元素,但不会改变数组的长度。

    注意:delete 操作符不会重新索引数组,也不会改变数组的 length 属性,因此通常不推荐在数组中使用它来删除元素。

4. 查找元素

  • indexOf(element, fromIndex): 返回数组中首次出现的指定元素的索引,未找到则返回 -1。

    注意:如果有多个相同的元素,indexOf 只返回第一个匹配的索引。
  • lastIndexOf(element, fromIndex): 返回数组中最后一次出现的指定元素的索引,未找到则返回 -1。

    注意:如果有多个相同的元素,lastIndexOf 会返回最后一个匹配的索引。 fromIndex 参数可以用来限制查找的范围,如果是负数,则从数组末尾的偏移量开始查找。
  • find(callback, thisArg): 返回数组中第一个符合条件的元素,找不到则返回 undefined。

返回值:返回第一个满足测试条件的元素。如果没有找到,返回 undefined。

点击查看代码
const numbers = [1, 3, 5, 7, 9];

// 查找第一个大于 4 的数字
const found = numbers.find(num => num > 4);
console.log(found); // 5

// 查找第一个为偶数的数字
const even = numbers.find(num => num % 2 === 0);
console.log(even); // undefined (因为数组中没有偶数)

const people = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Jack', age: 35 }
];

// 查找第一个年龄大于 30 的人
const person = people.find(person => person.age > 30);
console.log(person); // { name: 'Jack', age: 35 }
  • findIndex(callback, thisArg): 返回数组中第一个符合条件的元素的索引,找不到则返回 -1。
点击查看代码
const numbers = [10, 20, 30, 40, 50];

// 查找第一个大于 25 的数字的索引
const index = numbers.findIndex(num => num > 25);
console.log(index); // 2 (因为 30 是第一个大于 25 的数字)

const people = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Jack', age: 35 }
];

// 查找第一个年龄大于 30 的人的索引
const personIndex = people.findIndex(person => person.age > 30);
console.log(personIndex); // 2 (因为 Jack 是第一个年龄大于 30 的人)

// 查找第一个年龄小于 20 的人的索引
const noPersonIndex = people.findIndex(person => person.age < 20);
console.log(noPersonIndex); // -1 (因为没有人年龄小于 20)

返回值:返回满足条件的第一个元素的索引。如果没有找到符合条件的元素,则返回 -1。

  • includes(element, fromIndex): 判断数组是否包含指定元素,返回布尔值。


返回值:如果数组中包含 valueToFind,则返回 true;否则返回 false。
注意:该方法适用于基本数据类型的元素,但对 NaN 特殊处理。includes 可以正确识别 NaN(即 NaN 被认为是等于 NaN)。

  • some(callback, thisArg): 判断数组中是否至少有一个元素符合条件,返回布尔值。
点击查看代码
const numbers = [1, 2, 3, 4, 5];

// 检查是否存在大于 3 的元素
const hasLargeNumber = numbers.some(num => num > 3);
console.log(hasLargeNumber); // true (因为 4 和 5 大于 3)

// 检查是否存在小于 0 的元素
const hasNegativeNumber = numbers.some(num => num < 0);
console.log(hasNegativeNumber); // false

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

// 检查是否有年龄大于 30 的人
const hasOlderPerson = people.some(person => person.age > 30);
console.log(hasOlderPerson); // true (因为 Charlie 年龄大于 30)

返回值:如果至少有一个元素满足测试条件,则返回 true;否则返回 false。
注意:some 方法可以用于检查数组中是否存在满足特定条件的元素,而不需要遍历整个数组。

  • every(callback, thisArg): 判断数组中是否所有元素都符合条件,返回布尔值。
点击查看代码
const numbers = [2, 4, 6, 8, 10];

// 检查是否所有元素都是偶数
const allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // true

// 检查是否所有元素都大于 0
const allPositive = numbers.every(num => num > 0);
console.log(allPositive); // true

// 检查是否所有元素都大于 5
const allGreaterThanFive = numbers.every(num => num > 5);
console.log(allGreaterThanFive); // false (因为 2 和 4 不大于 5)
const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];
// 检查是否所有人年龄都在 20 到 40 岁之间
const allInRange = people.every(person => person.age >= 20 && person.age <= 40);
console.log(allInRange); // true
// 检查是否所有人都叫 Bob
const allBob = people.every(person => person.name === 'Bob');
console.log(allBob); // false (因为除了 Bob 外,还有 Alice 和 Charlie)

返回值:如果数组中的每个元素都通过了测试函数,则返回 true;否则返回 false。
注意:every 方法适用于检查数组中所有元素是否符合某些条件,而不需要遍历整个数组直到第一个不符合条件的元素为止

5. 遍历数组

  • forEach(callback, thisArg): 对数组的每个元素执行一次回调函数。

点击查看代码
const numbers = [1, 2, 3, 4, 5];

// 输出数组中的每个数字
numbers.forEach(num => {
  console.log(num);
});
// 输出:
// 1
// 2
// 3
// 4
// 5

// 计算数组中每个元素的平方,并存储到一个新数组中
const squares = [];
numbers.forEach(num => {
  squares.push(num * num);
});
console.log(squares); // [1, 4, 9, 16, 25]

// 使用索引参数
numbers.forEach((num, index) => {
  console.log(`Index ${index}: ${num}`);
});
// 输出:
// Index 0: 1
// Index 1: 2
// Index 2: 3
// Index 3: 4
// Index 4: 5

// 使用 thisArg 参数
const multiplier = {
  factor: 2
};

numbers.forEach(function(num) {

  console.log(num * this.factor); //factor 循环第二个参数的使用,multiplier必须是个对象,基础的变量不可以
}, multiplier);
// 输出:
// 2
// 4
// 6
// 8
// 10

返回值:forEach 方法没有返回值。它只是对数组中的每个元素执行回调函数。
注意:forEach 方法不会对原数组进行修改,但回调函数可以修改数组的内容。
注意:forEach 方法总是遍历整个数组,不会中途终止。如果需要在遇到特定条件时停止遍历,可以考虑使用 for 循环或其他数组方法(如 some 或 every)。
注意:forEach 不能被用于返回一个新的数组或过滤元素。对于这些需求,通常可以使用 map 或 filter 方法。

  • map(callback, thisArg): 返回一个新数组,其中每个元素是回调函数的结果。
点击查看代码
const numbers = [1, 2, 3, 4, 5];

// 创建一个新数组,元素是原数组每个元素的平方
const squares = numbers.map(num => num * num);
console.log(squares); // [1, 4, 9, 16, 25]

// 转换字符串数组中的每个字符串为大写
const words = ['hello', 'world', 'javascript'];
const uppercasedWords = words.map(word => word.toUpperCase());
console.log(uppercasedWords); // ['HELLO', 'WORLD', 'JAVASCRIPT']

// 使用索引参数
const arrayWithIndices = numbers.map((num, index) => `${index}: ${num}`);
console.log(arrayWithIndices); // ['0: 1', '1: 2', '2: 3', '3: 4', '4: 5']

// 使用 thisArg 参数
const multiplier = {
  factor: 3
};

const multipliedNumbers = numbers.map(function(num) {
  return num * this.factor;
}, multiplier);
console.log(multipliedNumbers); // [3, 6, 9, 12, 15]

返回值:一个新数组,其中每个元素是 callback 函数返回的结果。
注意:map 方法创建的新数组长度与原数组相同。
注意:map 不会修改原数组,但回调函数可以
注意:如果需要对数组进行过滤和转换,map 和 filter 可以一起使用,例如先用 filter 过滤数据,再用 map 进行转换。

  • filter(callback, thisArg): 返回一个新数组,其中包含所有通过测试的元素。
点击查看代码
const numbers = [1, 2, 3, 4, 5];

// 创建一个新数组,包含所有大于 2 的元素
const greaterThanTwo = numbers.filter(num => num > 2);
console.log(greaterThanTwo); // [3, 4, 5]

// 过滤掉数组中的负数
const mixedNumbers = [1, -2, 3, -4, 5];
const positiveNumbers = mixedNumbers.filter(num => num > 0);
console.log(positiveNumbers); // [1, 3, 5]

// 使用索引参数
const words = ['apple', 'banana', 'cherry'];
const longWords = words.filter((word, index) => word.length > 5);
console.log(longWords); // ['banana', 'cherry']

// 使用 thisArg 参数
const threshold = {
  min: 3
};

const filteredNumbers = numbers.filter(function(num) {
  return num >= this.min;
}, threshold);
console.log(filteredNumbers); // [3, 4, 5]

返回值:一个新数组,其中包含所有通过 callback 函数测试的元素。
注意:filter 返回的新数组只包含通过测试的元素,原数组不受影响。
注意:filter 方法不会修改原数组,但回调函数可以。
注意:使用 filter 方法可以有效地从数组中删除不符合条件的元素。

  • reduce(callback, initialValue): 对数组的每个元素执行回调函数,返回单一值。
点击查看代码
const numbers = [1, 2, 3, 4, 5];

// 计算数组所有元素的和
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 15

// 计算数组所有元素的乘积
const product = numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
console.log(product); // 120

// 找到数组中最大的数
const max = numbers.reduce((maxValue, currentValue) => Math.max(maxValue, currentValue));
console.log(max); // 5

// 按元素长度合并字符串
const words = ['apple', 'banana', 'cherry'];
const concatenated = words.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(concatenated); // 'applebananacherry'

// 使用初始值的示例
const numbersWithInitial = [2, 3, 4];
const initialValueSum = numbersWithInitial.reduce((accumulator, currentValue) => accumulator + currentValue, 10);
console.log(initialValueSum); // 19

返回值:reduce 返回经过所有累加操作后的最终值。
注意:reduce 方法对数组中的每个元素都执行一次 callback 函数,最终返回一个值。
注意:如果提供了 initialValue,callback 的第一次调用时 accumulator 为 initialValue;如果没有提供,callback 的第一次调用时 accumulator 为数组的第一个元素。
注意:reduce 不会修改原数组,但回调函数可以。

  • reduceRight(callback, initialValue): 从数组的末尾开始对每个元素执行回调函数,返回单一值。
点击查看代码
const numbers = [1, 2, 3, 4, 5];

// 从右向左计算数组所有元素的和
const sumRight = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sumRight); // 15

// 从右向左计算数组所有元素的乘积
const productRight = numbers.reduceRight((accumulator, currentValue) => accumulator * currentValue, 1);
console.log(productRight); // 120

// 从右向左找到数组中最大的数
const maxRight = numbers.reduceRight((maxValue, currentValue) => Math.max(maxValue, currentValue));
console.log(maxRight); // 5

// 从右向左合并字符串
const words = ['apple', 'banana', 'cherry'];
const concatenatedRight = words.reduceRight((accumulator, currentValue) => accumulator + currentValue);
console.log(concatenatedRight); // 'cherrybananapple'

// 使用初始值的示例
const numbersWithInitial = [2, 3, 4];
const initialValueSumRight = numbersWithInitial.reduceRight((accumulator, currentValue) => accumulator + currentValue, 10);
console.log(initialValueSumRight); // 19
`返回值:reduceRight 返回经过所有累加操作后的最终值。` `注意:reduceRight 方法从数组的右端开始进行迭代,与 reduce 从左端开始迭代不同。` `注意:如果提供了 initialValue,callback 的第一次调用时 accumulator 为 initialValue;如果没有提供,callback 的第一次调用时 accumulator 为数组的最后一个元素。` `注意:reduceRight 不会修改原数组,但回调函数可以。`
  • flat(depth): 将多维数组“拍平”,可以指定拍平的深度。
点击查看代码
const nestedArray = [1, [2, [3, [4, 5]]]];
// 默认深度为 1
const flatOnce = nestedArray.flat();
console.log(flatOnce); // [1, 2, [3, [4, 5]]]

// 深度为 2 ;注意:对于深度较大的数组或需要拍平所有层级时,可以使用 Infinity 作为深度参数;
const flatTwice = nestedArray.flat(2);
console.log(flatTwice); // [1, 2, 3, [4, 5]]

// 深度为 Infinity
const flatAll = nestedArray.flat(Infinity);
console.log(flatAll); // [1, 2, 3, 4, 5]

// 空数组的示例
const emptyArray = [].flat();
console.log(emptyArray); // []

// 带有非数组元素的示例
const mixedArray = [1, 2, [3, 4], 'hello', [5, [6]]];
const mixedFlat = mixedArray.flat();
console.log(mixedFlat); // [1, 2, 3, 4, 'hello', 5, [6]]

返回值:返回一个新的数组,包含所有嵌套数组的元素,按指定的深度拍平。
注意:flat() 方法不会修改原数组,而是返回一个新的数组。
注意:depth 参数控制拍平的层级。如果省略或设置为 1,仅会拍平一层嵌套的数组。
注意:对于深度较大的数组或需要拍平所有层级时,可以使用 Infinity 作为深度参数。

  • flatMap(callback, thisArg): 对每个元素应用回调函数,然后将结果“拍平”至一维数组。
点击查看代码
const numbers = [1, 2, 3, 4];

// 使用 flatMap 将每个数字变成一个数组并拍平
const mappedAndFlattened = numbers.flatMap(x => [x, x * 2]);
console.log(mappedAndFlattened); // [1, 2, 2, 4, 3, 6, 4, 8]

// 对象数组示例
const sentences = [
  'The quick brown fox',
  'jumps over the lazy dog'
];

// 将每个句子分割成单词,并拍平结果
const words = sentences.flatMap(sentence => sentence.split(' '));
console.log(words); // ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

// 空数组的示例
const empty = [].flatMap(x => [x]);
console.log(empty); // []

返回值:返回一个新数组,包含将所有子数组拍平后的结果。
flatMap() 方法不会修改原数组,而是返回一个新数组。
默认情况下,flatMap() 只拍平一层嵌套的数组。要处理更多层次的嵌套,可以先使用 map() 再使用 flat()。

6. 变换数组

  • concat(...arrays): 合并两个或多个数组。
  • slice(begin, end): 返回数组的一个片段(浅拷贝),包含 begin 索引到 end 索引(不包括 end 索引)的元素。
  • join(separator): 将数组的所有元素连接成一个字符串。
  • sort(compareFunction): 对数组进行排序,可以指定排序函数。
  • reverse(): 颠倒数组中元素的顺序。

7. 其他

  • copyWithin(target, start, end): 将数组的指定部分复制到另一个位置。
  • fill(value, start, end): 用指定的值填充数组的部分或全部元素。
  • from(iterable, mapFn, thisArg): 从类数组或可迭代对象创建数组,可以应用映射函数。
  • toString(): 将数组转换为字符串。
  • toLocaleString(): 将数组转换为本地化的字符串。

8. ES2022+ 方法

  • at(index): 返回数组中指定位置的元素,可以使用负数索引。
  • groupBy(callback): 将数组中的元素按回调函数的返回值分组(需要 polyfill)。
  • groupByToMap(callback): 与 groupBy 类似,但返回的是 Map(需要 polyfill)。
posted on 2024-08-25 10:49  好久不见-库克  阅读(2)  评论(0编辑  收藏  举报