js数组方法(大全)

  1. Array.at() 通过下标获取数值

Array.at(index) 获取对应下标的数值,index为下标值,正数时从左往右查询,负数时从右往左查询(默认值为0)。示例如下:

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

let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// Expected output: "Using an index of 2 the item returned is 8"

index = -2;

console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// Expected output: "Using an index of -2 item returned is 130"

  1. Array.concat 数组拼接

拼接两个数组或者多个数组,返回的是新数组,不会改变原数组。示例如下:

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// Expected output: Array ["a", "b", "c", "d", "e", "f"]

  1. Array.entries() 数组迭代器对象

会一层一层迭代下下去,该对象包含数组中每个索引的键/值对。示例如下:

示例一:
const array1 = ['a', 'b', 'c'];

const iterator1 = array1.entries();

console.log(iterator1.next().value);
// Expected output: Array [0, "a"]

console.log(iterator1.next().value);
// Expected output: Array [1, "b"]

console.log(iterator1.next().value);
// Expected output: Array [2, "c"]

示例二:
const a = ["a", "b", "c"];

for (const [index, element] of a.entries()) {
  console.log(index, element);
}
// 0 'a'
// 1 'b'
// 2 'c'

示例三:
const array = ["a", "b", "c"];
const arrayEntries = array.entries();

for (const element of arrayEntries) {
  console.log(element);
}

// [0, 'a']
// [1, 'b']
// [2, 'c']

  1. Array.every() 判断指定元素是否通过测试(返回值为布尔值)

Array.every (element, index. array) 方法测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值。有三个参数,对应如下:

element

index

array

数组中正在处理的当前元素

下标

调用 every 的当前数组

示例如下:

示例一:
const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// Expected output: true

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

  1. Array.fill() 填充修改数组

Array.fill(value, statr, end ) 方法用一个固定值填充一个数组中从起始索引(默认为 0)到终止索引(默认为 array.length)内的全部元素。它返回修改后的数组。

value

statr

end

改变的值

改变的下标

示例如下:

console.log([1, 2, 3].fill(4)); // [4, 4, 4]
console.log([1, 2, 3].fill(4, 1)); // [1, 4, 4]
console.log([1, 2, 3].fill(4, 1, 2)); // [1, 4, 3]
console.log([1, 2, 3].fill(4, 1, 1)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 3)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, -3, -2)); // [4, 2, 3]
console.log([1, 2, 3].fill(4, NaN, NaN)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 5)); // [1, 2, 3]
console.log(Array(3).fill(4)); // [4, 4, 4]

Array.filter() 数组过滤,筛选

Array.filter(element, index, array) 不会改变原数组,创建一个新的数组

element

index

array

数组中当前正在处理的元素。

正在处理的元素在数组中的索引。

调用了 filter() 的数组本身。

示例如下

示例一:
筛选排除对比小的值
function isBigEnough(value) {
  return value >= 10;
}

const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

示例二:
找出下列输入所有质数
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

function isPrime(num) {
  for (let i = 2; num > i; i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return num > 1;
}

console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]

示例三:
在数组中搜索
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

/**
 * 根据搜索条件(查询)筛选数组项
 */
function filterItems(arr, query) {
    return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));
}

console.log(filterItems(fruits, 'ap')); // ['apple', 'grapes']
console.log(filterItems(fruits, 'an')); // ['banana', 'mango', 'orange']

  1. Array.find() 返回测试中第一个满足的元素的值

Array.find(element, index, array) 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

element

index

array

当前遍历到的元素。

当前遍历到的索引。

数组本身。

示例如下:

示例一:
const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5},
  {name: 'cherries', quantity: 6}
];

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

console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }
// 只会返回满足条件的第一个数据

示例二:
使用箭头函数和解构赋值
const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find(({ name }) => name === 'cherries');

console.log(result) // { name: 'cherries', quantity: 5 }

  1. Array.findIndex() 查询到满足的条件,返回对应下标,否则返回-1

Array.findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1(下标从0开始)。

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

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

console.log(array1.findIndex(isLargeNumber));
// Expected output: 3

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

console.log(array1.findIndex(isLargeNumber));
// Expected output: -1

  1. Array.findLast() 查询到满足的条件,返回对应下标,否则返回undefined

findLast() 方法返回数组中满足提供的测试函数条件的最后一个元素的值。如果没有找到对应元素,则返回 undefined (下标从0开始)。

示例如下:

示例一:
const array1 = [5, 12, 50, 130, 44];

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

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

示例二:
const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'fish', quantity: 1},
  {name: 'cherries', quantity: 5}
];

// return true inventory stock is low
function isNotEnough(item) {
  return item.quantity < 2;
}

console.log(inventory.findLast(isNotEnough));
// { name: "fish", quantity: 1 }

  1. Array.findLastIndex() 返回满足条件最后一个索引,没有找到则返回-1

Array.findLastIndex() 方法返回数组中满足提供的测试函数条件的最后一个元素的索引。若没有找到对应元素,则返回 -1。(下标从0开始)

示例如下:

示例一:
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

示例二:
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];

const index = fruits.findLastIndex(fruit => fruit === "blueberries");

console.log(index); // 3
console.log(fruits[index]); // blueberries

  1. Array.flat() 递归遍历数组

Array.flat(depth) 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

depth

指定要提取嵌套数组的结构深度,默认值为 1。

示例如下:

const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// Expected output: Array [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];

console.log(arr2.flat(2));
// Expected output: Array [0, 1, 2, Array [3, 4]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

  1. Array.forEach() 循环数组

Array.forEach(element, index, array) 方法对数组的每个元素执行一次给定的函数

element

index

array

数组中正在处理的当前元素。

数组中正在处理的当前元素的索引。

forEach() 方法正在操作的数组。

示例如下:

示例一:
const array1 = ['a', 'b', 'c'];

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

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

示例二:
const ratings = [5, 4, 5];
let sum = 0;

const sumFunction = async (a, b) => a + b;
ratings.forEach(async (rating) => {
  sum = await sumFunction(sum, rating);
});

console.log(sum);
// 期望的输出:14
// 实际的输出:0

  1. Array.from() 类似数组或可迭代对象创建一个新的,浅拷贝的数组实例

Array.from() 方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。示例如下:

示例一:
// 将string字符串转换为数组
Array.from('foo');
// [ "f", "o", "o" ]

示例二:
// 从set生成数组
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]
// new Set可以去重

示例三:
// 从Map生成数组
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];

Array.from(mapper.keys());
// ['1', '2'];

示例四:
// 从类数组对象生成数组
function f() {
  return Array.from(arguments);
}

f(1, 2, 3);
// [ 1, 2, 3 ]

示例五: 
// 数组去重合并
function combine(){
    let arr = [].concat.apply([], arguments);  //没有去重复的新数组
    return Array.from(new Set(arr));
}

var m = [1, 2, 2], n = [2,3,3];
console.log(combine(m,n));                     // [1, 2, 3]

  1. Array.includes() 判断数组是否有那个值,反回布尔值

includes(searchElement, fromIndex ) 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。可传递两个参数

searchElement

fromIndex (可选)

需要查找的元素值。

从fromIndex 索引处开始查找 searchElement。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜(即使从末尾开始往前跳 fromIndex 的绝对值个索引,然后往后搜寻)。默认为 0。

示例如下:

示例一:
const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

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

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

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

示例二:
// 如果 fromIndex 大于等于数组的长度,则将直接返回 false,且不搜索该数组。
var arr = ['a', 'b', 'c'];

arr.includes('c', 3);   // false
arr.includes('c', 100); // false

  1. Array.indexOf() 查找满足的第一个值,返回下标

Array.indexOf(searchElement, fromIndex ) 方法返回在数组中可以找到给定元素的第一个索引,如果不存在,则返回 -1。(返回的下标从0开始计算)

searchElement

fromIndex

要查找的元素。

开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回 -1。如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即 -1 表示从最后一个元素开始查找,-2 表示从倒数第二个元素开始查找,以此类推。注意:如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。如果抵消后的索引值仍小于 0,则整个数组都将会被查询。其默认值为 0。

示例如下:

示例一:
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1

示例二:
const array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

示例三:
// 找出指定元素出现的所有位置
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]

  1. Array.isArray() 判断是不是数组,返回值为布尔值

Array.isArray(value) 用于确定传递的值是否是一个 Array。

返回值:如果是Array则返回true,否则返回false

value

需要检测的值

示例如下:

示例一:
// 下面的函数调用都返回 true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array('a', 'b', 'c', 'd'))
Array.isArray(new Array(3));
// 鲜为人知的事实:其实 Array.prototype 也是一个数组。
Array.isArray(Array.prototype);

// 下面的函数调用都返回 false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32))
Array.isArray({ __proto__: Array.prototype });

  1. Array.join() 将数组转换为字符串

Array.join(separator) 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。如果数组只有一个元素,那么将返回该元素而不使用分隔符。

separator

指定一个字符串来分隔数组的每个元素。如果需要,将分隔符转换为字符串。如果省略,数组元素用逗号(,)分隔。如果 separator 是空字符串(""),则所有元素之间都没有任何字符。

示例如下:

示例一:
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"

示例二:
const a = ['Wind', 'Water', 'Fire'];
a.join();      // 'Wind,Water,Fire'
a.join(', ');  // 'Wind, Water, Fire'
a.join(' + '); // 'Wind + Water + Fire'
a.join('');    // 'WindWaterFire'

  1. Array.keys() 返回数组的下标

Array,keys() 方法返回一个包含数组中每个索引键的 Array Iterator 对象。

示例如下:

示例一:
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

// Expected output: 0
// Expected output: 1
// Expected output: 2

  1. Array.lastIndexOf() 查找指定元素,返回最后一个找到的下标

Array.lastIndexOf(searchElement, fromIndex) 方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。(返回的下标从0开始)

searchElement

被查找的元素。

fromIndex

从此位置开始逆向查找。默认为数组的长度减 1(arr.length - 1),即整个数组都被查找。如果该值大于或等于数组的长度,则整个数组会被查找。如果为负值,将其视为从数组末尾向前的偏移。即使该值为负,数组仍然会被从后向前查找。如果该值为负时,其绝对值大于数组长度,则方法返回 -1,即数组不会被查找。

示例如下:

示例一:
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// Expected output: 3

console.log(animals.lastIndexOf('Tiger'));
// Expected output: 1

示例二:
var array = [2, 5, 9, 2];
var index = array.lastIndexOf(2);
// index is 3
index = array.lastIndexOf(7);
// index is -1
index = array.lastIndexOf(2, 3);
// index is 3
index = array.lastIndexOf(2, 2);
// index is 0
index = array.lastIndexOf(2, -2);
// index is 0
index = array.lastIndexOf(2, -1);
// index is 3

示例三:
var array = [2, 5, 9, 2];
var index = array.lastIndexOf(2);
// index is 3
index = array.lastIndexOf(7);
// index is -1
index = array.lastIndexOf(2, 3);
// index is 3
index = array.lastIndexOf(2, 2);
// index is 0
index = array.lastIndexOf(2, -2);
// index is 0
index = array.lastIndexOf(2, -1);
// index is 3

  1. Array.map() 遍历数组

Array.map(currentValue, index, array) 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。

currentValue

callbackFn 数组中正在处理的当前元素。

index

callbackFn 数组中正在处理的当前元素的索引

array

map 方法调用的数组。

示例如下:

示例一:
const array1 = [1, 4, 9, 16];

// Pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// Expected output: Array [2, 8, 18, 32]

array1.map((item,index,arr) => {
  console.log(item,index,arr)
})
// 1 0 Array [1, 4, 9, 16]
// 4 1 Array [1, 4, 9, 16]
// 9 2 Array [1, 4, 9, 16]
// 16 3 Array [1, 4, 9, 16]

  1. Array.pop() 从一个数组中删除并返回最后一个元素。

Array.pop() 方法从数组中删除最后一个元素,并返回该元素的值。如果你在一个空数组上调用 pop(),它将返回 undefined。此方法会更改数组的长度(会改变原数组)。

示例如下:

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// Expected output: "tomato"

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

plants.pop();

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

示例二:
const myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

const popped = myFish.pop();

console.log(myFish); // ['angel', 'clown', 'mandarin']

console.log(popped); // 'sturgeon'

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/push

猜你喜欢

转载自blog.csdn.net/zzll1216/article/details/129688379