你不会还不知道数组里面有这些好用的方法吧!(JavaScript)

41 篇文章 7 订阅
39 篇文章 3 订阅

在JavaScript我们常常会对数组进行很多需求上的操作,比如求取数组中的偶数,或者是查找数组中的某一个值。如果我们使用for循环的方法进行遍历数组,进行需求操作。往往效率很低,并且吃力不讨好。这时我们就可以使用JavaScript里数组的内置函数来对数组进行操作。这样效率不仅会大大提高还可以减轻我们编写代码的压力,使得我们编写的代码看起来更加简洁。

接下来我们就详细介绍一下我们数组中的经常使用方法

首先是创建我们将要操作的的数组

创建数组的方式

直接方括号+元素内容这种形式

const arr = [1, 2, 3, 4]   

利用构造函数创建数组

const arr = new Array()
const arr = new Array(7)

遍历和访问数组的方式

for 循环

// 获取数组的长度
const len = arr.length
for(let i=0;i<len;i++) {
    // 输出数组的元素值,输出当前索引
    console.log(arr[i], i)
}

forEach 方法

forEach() 方法:对数组的每个元素执行一次给定的函数。无返回值,不可链式调用

语法

  • forEach( (element) => { /* … */ })
  • forEach( (element, index) => { /* … */ })
  • forEach( (element, index, array) => { /* … */ })

element:数组中正在处理的当前元素。
index:数组中正在处理的当前元素的索引。
array:forEach() 方法正在操作的数组。

arr.forEach((item, index)=> {
    // 输出数组的元素值,输出当前索引
    console.log(item, index)
})

map 方法

map 方法在调用形式上与 forEach 无异,区别在于 map 方法会根据你传入的函数逻辑对数组中每个元素进行处理、进而返回一个全新的数组。
所以其实 map 做的事情不仅仅是遍历,而是在遍历的基础上“再加工”。当我们需要对数组内容做批量修改、同时修改的逻辑又高度一致时,就可以调用 map 来达到我们的目的。(map只会在有值的索引上调用;那些从来没被赋过值或者使用 delete 删除的索引则不会被调用。)

语法:

  • map( (element) => { /* … */ })
  • map( (element, index) => { /* … */ })
  • map( (element, index, array) => { /* … */ })

currentValue:数组中正在处理的当前元素。
index:数组中正在处理的当前元素的索引。
array:当前正在调用的数组。

const newArr = arr.map( (item, index)=> {
    // 输出数组的元素值,输出当前索引
    console.log(item, index)
    // 在当前元素值的基础上加1,返回一个全新的数组
    return item+1
})

reduce方法

reducer()方法: 逐个遍历数组元素,每一步都将当前元素的值与上一步的计算结果相加(上一步的计算结果是当前元素之前所有元素的总和)——直到没有更多的元素被相加。且会把最终结果返回。

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

语法:

  • reduce( (previousValue, currentValue) => { /* … */ } , initialValue)
  • reduce( (previousValue, currentValue, currentIndex) => { /* … */ } , initialValue)
  • reduce( (previousValue, currentValue, currentIndex, array) => { /* … */ }, initialValue(可选))

previousValue:上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值 initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]。
currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]。
currentIndex:数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始。
array:用于遍历的数组。
initialValue(可选):作为第一次调用 callback 函数时参数 previousValue 的值。若指定了初始值 initialValue,则 currentValue 则将使用数组第一个元素;否则 previousValue 将使用数组第一个元素,而 currentValue 将使用数组第二个元素。

const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
);
console.log(sumWithInitial);
//  10

reduceRight方法

reduceRight() 方法接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。

语法:

  • reduceRight((accumulator, currentValue) => { /* … */ } )
  • reduceRight((accumulator, currentValue, index) => { /* … */ } )
  • reduceRight((accumulator, currentValue, index, array) => { /* … */ } )
  • reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue)

accumulator:累加器:上一次调用回调函数时,回调函数返回的值。首次调用回调函数时,如果 initialValue 存在,累加器即为 initialValue,否则须为数组中的最后一个元素(详见下方 initialValue 处相关说明)。
currentValue:当前元素:当前被处理的元素。
index:数组中当前被处理的元素的索引。
array:调用 reduceRight() 的数组。
initialValue:首次调用 callback 函数时,累加器 accumulator 的值。如果未提供该初始值,则将使用数组中的最后一个元素,并跳过该元素。如果不给出初始值,则需保证数组不为空。 否则,在空数组上调用 reduce 或 reduceRight 且未提供初始值(例如 [].reduce( (acc, cur, idx, arr) => {} ) )的话,会导致类型错误 TypeError: reduce of empty array with no initial value。

const array1 = [[0, 1], [2, 3], [4, 5]];
const result = array1.reduceRight(
(accumulator, currentValue) => accumulator.concat(currentValue));
console.log(result);
// expected output: Array [4, 5, 2, 3, 0, 1]

数组中增加元素的方法

push方法

push方法是在数组最后面添加元素,可以添加多个。而且push方法会返回新数组的长度

语法:

  • push(element0)
  • push(element0, element1)
  • push(element0, element1, /* … ,*/ elementN)

elementN:被添加到数组末尾的元素。

var arr = [1, 2, 3, 4]   
arr.push(5)
console.log(arr) //[1, 2, 3, 4, 5]
arr.push(6,7) 
console.log(arr) //[1, 2, 3, 4, 5, 6, 7]
let arrLen = arr.push()
console.log(arrLen) // 7

unshift 方法

unshift()方法(在开头)向数组添加新元素,并“反向位移”旧元素,并且返回新数组的长度。可以添加多个元素。

var arr = [1, 2, 3, 4]
arr.unshift(0)
console.log(arr) //[ 0, 1, 2, 3, 4 ]
let arrLen = arr.unshift()
console.log(arrLen) // 5
arr.unshift(0,0)
console.log(arr)//[0, 0, 0, 1, 2, 3, 4]

splice 方法-添加元素到数组的任何位置

splice()方法:删除元素/插入元素/替换元素 splice(‘从第几个元素开始’,‘删除几个元素’,‘要替换或者要加入的元素、可以是多个’)

var arr = [1, 2, 3, 4]   
//在第0 位删除0个元素,添加0
arr.splice(00,0)

数组中删除元素的方法

pop 方法

pop() 方法从数组中删除最后一个元素,而且会返回“被弹出”的值(当数组为空时返回undefined)。

语法:pop()

var arr = [1, 2, 3, 4]   
arr.pop()
console.log(arr) //[ 1, 2, 3 ]
let arrDelVal = arr.pop()
console.log(arrDelVal) // 3

shift 方法

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

语法:shift()

const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
//  Array [2, 3]
console.log(firstElement);
//  1

splice 方法

splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
splice(‘从第几个元素开始’,‘删除几个元素’,‘要替换或者要加入的元素、可以是多个’)

说明:

  • splice(start)
  • splice(start, deleteCount)
  • splice(start, deleteCount, item1)
  • splice(start, deleteCount, item1, item2, itemN)

start:指定修改的开始位置(从 0 计数)。如果超出了数组的长度,则从数组末尾开始添加内容;如果是负值,则表示从数组末位开始的第几位(从 -1 计数,这意味着 -n 是倒数第 n 个元素并且等价于 array.length-n);如果负数的绝对值大于数组的长度,则表示开始位置为第 0 位。
deleteCount 可选:整数,表示要移除的数组元素的个数。如果 deleteCount 大于 start 之后的元素的总数,则从 start 后面的元素都将被删除(含第 start 位)。如果 deleteCount 被省略了,或者它的值大于等于array.length - start(也就是说,如果它大于或者等于start之后的所有元素的数量),那么start之后数组的所有元素都会被删除。如果 deleteCount 是 0 或者负数,则不移除元素。这种情况下,至少应添加一个新元素。
item1, item2, … 可选:要添加进数组的元素,从start 位置开始。如果不指定,则 splice() 将只删除数组元素。

var arr = [1, 2, 3, 4]   
//在第3位删除1个元素
arr.splice(31

对数组进行排序的方法

sort方法

sort()方法:默认把数组按照升序排序 。
升序:x-y;降序:y-x

:果没有指明 的传入回调函数 ,那么元素会按照转换为的字符串的诸个字符的 Unicode 位点进行排序。例如 “Banana” 会被排列到 “cherry” 之前。当数字按由小到大排序时,9 出现在 80 之前,但因为(没有指明 compareFn),比较的数字会先被转换为字符串,所以在 Unicode 顺序上 “80” 要比 “9” 要靠前。
如果指明了 回调函数 ,那么数组会按照调用该函数的返回值排序。即 a 和 b 是两个将要被比较的元素:
如果 compareFn(a, b) 大于 0 , b 会被排列到 a 之前。
如果 compareFn(a, b) 小于 0 ,那么 a 会被排列到 b 之前;
如果 compareFn(a, b) 等于 0 , a 和 b 的相对位置不变。备注: ECMAScript 标准并不保证这一行为,而且也不是所有浏览器都会遵守(例如 Mozilla 在 2003 年之前的版本);

语法:

  • 无函数:sort()
  • 箭头函数:sort((a, b) => { /* … */ } )
  • 比较函数:sort(compareFn)
  • 内联比较函数:sort(function compareFn(a, b) { /* … */ })
//(x和y是两个相邻的数据元素。当function(x,y)得到的返回值小于0,x会被移动到y前面,如果得到的返回值大于0,x会被移动到y后面,当得到的返回值等于0,x和y的位置相对不变。)
var arr = [1, 4, 3, 2]  
arr.sort(function(){
return x-y;
})

reverse方法

reverse()方法:把数组倒序

var arr = [1,2,3,4]  
arr.reverse()
//4,3,2,1

reverse方法

reverse() 方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。

语法:

  • reverse()
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
//Array ["three", "two", "one"]

console.log('array1:', array1);
//"array1:" Array ["three", "two", "one"]

把数组转换为字符串的方法

toString方法

toString()方法:把数组转换为数组值(逗号分隔)的字符串。

var arr = ["a", "b", "c", "d"]

console.log(arr.toString()) //"a,b,c,d"

join方法

join()方法:是将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。。默认分隔符是逗号 (,),join() 方法不会改变原始数组

var arr = ["a", "b", "c", "d"]
console.log(arr.join(" - "))
console.log() //a - b - c - d

toLocaleString方法

语法:

  • toLocaleString();
  • toLocaleString(locales);
  • toLocaleString(locales, options);

locales:带有 BCP 47 语言标记的字符串或字符串数组.
options:一个可配置属性的对象。

const array1 = [1, 'a',2,6,8,1,3,5];
const localeString = array1.toLocaleString();
console.log(localeString);
// "1,a,2,6,8,1,3,5"

合并(连接数组)的方法

concat方法

concat()方法:不会改变现有的种类,而是不同的返回一个新的数组,把两个数组合并成一个新的数组。并且对数组数量没有限制。而且也可以把值作为参数传入合并

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = ["g", "h"];
const array4 = array1.concat(array2);
console.log(array4); // ["a", "b", "c", "d", "e", "f"]
const array5 = array1.concat(array2,array3);
console.log(array5); // ["a", "b", "c", "d", "e", "f", "g", "h"]
const array6 = array1.concat(array2,[2,3]);
console.log(array6); //["a", "b", "c", "d", "e", "f", 2, 3]

flat方法

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

语法:

  • flat()
  • flat(depth)

depth(可选):指定要提取嵌套数组的结构深度,默认值为 1。

var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

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

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

//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

//flat() 方法会移除数组中的空项
var arr4 = [1, 2, , 4, 5];
arr4.flat();
// [1, 2, 4, 5]

flatMap方法

flatMap() 方法:首先使用映射函数映射每个元素,然后将结果压缩成一个新数组返回。它与 map 连着深度值为 1 的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。

语法:

  • flatMap((currentValue) => { /* … */ } )
  • flatMap((currentValue, index) => { /* … */ } )
  • flatMap((currentValue, index, array) => { /* … */ } )

currentValue:当前正在数组中处理的元素。
index:可选的。数组中正在处理的当前元素的索引。
array:可选的。被调用的 map 数组。

var arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]

复制数组的方法

copyWithin方法

copyWithin() 方法浅复制数组的一部分到同一数组中的另一个位置,并返回它不会改变原数组的长度

语法:copyWithin(target, start, end)

target:是以0 为基底的索引,复制序列到该位置。如果是负数,target 将从末尾开始计算。如果 target 大于等于 arr.length,将不会发生拷贝。如果 target 在 start 之后,复制的序列将被修改以符合 arr.length。
start:是以0 为基底的索引,开始复制元素的起始位置。如果是负数,start 将从末尾开始计算。如果 start 被忽略,copyWithin 将会从 0 开始复制。
end:是以0 为基底的索引,开始复制元素的结束位置。copyWithin 将会拷贝到该位置,但不包括 end 这个位置的元素。如果是负数, end 将从末尾开始计算。如果 end 被忽略,copyWithin 方法将会一直复制至数组结尾(默认为 arr.length)。

[1, 2, 3, 4, 5].copyWithin(-2)
// [1, 2, 3, 1, 2]

[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(-2, -3, -1)
// [1, 2, 3, 3, 4]

[].copyWithin.call({length: 5, 3: 1}, 0, 3);
// {0: 1, 3: 1, length: 5}

// ES2015 Typed Arrays are subclasses of Array
var i32a = new Int32Array([1, 2, 3, 4, 5]);

i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// On platforms that are not yet ES2015 compliant:
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

slice方法

slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

语法:

  • slice()
  • slice(start)
  • slice(start, end)

begin:提取起始处的索引(从 0 开始),从该索引开始提取原数组元素。如果该参数为负数,则表示从原数组中的倒数第几个元素开始提取,slice(-2) 表示提取原数组中的倒数第二个元素到最后一个元素(包含最后一个元素)。如果省略 begin,则 slice 从索引 0 开始。如果 begin 超出原数组的索引范围,则会返回空数组。
end:提取终止处的索引(从 0 开始),在该索引处结束提取原数组元素。slice 会提取原数组中索引从 begin 到 end 的所有元素(包含 begin,但不包含 end)。slice(1,4) 会提取原数组中从第二个元素开始一直到第四个元素的所有元素(索引为 1, 2, 3 的元素)。如果该参数为负数, 则它表示在原数组中的倒数第几个元素结束抽取。 slice(-2,-1) 表示抽取了原数组中的倒数第二个元素到最后一个元素(不包含最后一个元素,也就是只有倒数第二个元素)。如果 end 被省略,则 slice 会一直提取到原数组末尾。如果 end 大于数组的长度,slice 也会一直提取到原数组末尾。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
//  Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
//  Array ["camel", "duck"]
console.log(animals.slice(1, 5));
//  Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
//  Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// Array ["camel", "duck"]
console.log(animals.slice());
// Array ["ant", "bison", "camel", "duck", "elephant"]

from方法

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

语法:

  • Array.from(arrayLike, (element) => { /* … */ } )
  • Array.from(arrayLike, (element, index) => { /* … */ } )

arrayLike:想要转换成数组的伪数组对象或可迭代对象。

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

对数组中的每一个元素进行检查

every方法

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

详细:every方法为数组中的每个元素执行一次 callback 函数,直到它找到一个会使 callback 返回 falsy 的元素。如果发现了一个这样的元素,every 方法将会立即返回 false。否则,callback 为每一个元素返回 true,every 就会返回 true。callback 只会为那些已经被赋值的索引调用。不会为那些被删除或从未被赋值的索引调用。

:every 遍历的元素范围在第一次调用 callback 之前就已确定了。在调用 every 之后添加到数组中的元素不会被 callback 访问到。如果数组中存在的元素被更改,则他们传入 callback 的值是 every 访问到他们那一刻的值。那些被删除的元素或从来未被赋值的元素将不会被访问到。
在every 中只有所有的元素都符合条件才会返回 true。正因如此,若传入一个空数组,无论如何都会返回 true。(这种情况属于无条件正确:正因为一个空集合没有元素,所以它其中的所有元素都符合给定的条件。)

语法

  • every((element) => { /* … */ } )、
  • every((element, index) => { /* … */ } )、
  • every((element, index, array) => { /* … */ } )

element:测试的当前值,可以拿到我们数组检测的当前值。
index:用于测试的当前值的索引。可以拿到我们数组检测的当前索引
array:调用 every 的当前数组。 可以拿到我们检测的数组

//基本写法
function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
//箭头函数的写法:
[12, 5, 8, 130, 44].every(x => x >= 10); // false
[12, 54, 18, 130, 44].every(x => x >= 10); // true

includes方法

includes() 方法:用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。
语法:

  • includes(searchElement)
  • includes(searchElement, fromIndex)

earchElement:需要查找的元素值。
fromIndex:从fromIndex 索引处开始查找 searchElement。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜(即使从末尾开始往前跳 fromIndex 的绝对值个索引,然后往后搜寻)。默认为 0。如果 fromIndex 大于等于数组的长度,则将直接返回 false,且不搜索该数组。如果 fromIndex 为负值,计算出的索引将作为开始搜索searchElement的位置。如果计算出的索引小于 0,则整个数组都会被搜索。

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true

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

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

//如果 fromIndex 为负值,计算出的索引将作为开始搜索searchElement的位置。如果计算出的索引小于 0,则整个数组都会被搜索。
// array length is 3
// fromIndex is -100
// computed index is 3 + (-100) = -97

var arr = ['a', 'b', 'c'];

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

some方法

some() 方法测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回的是一个 Boolean 类型的值。
语法:

  • some((element) => { /* … */ } )
  • some((element, index) => { /* … */ } )
  • some((element, index, array) => { /* … */ } )

element:当前遍历到的元素。
index:当前遍历到的索引。
array:被调用的数组。

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

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

填充数组

fill方法

fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。返回修改后的数组。

语法

  • fill(value)
  • fill(value, start)
  • fill(value, start, end)

value:用来填充数组元素的值。
start(可选):起始索引,默认值为 0。
end(可选):终止索引,默认值为 arr.length。

[1, 2, 3].fill(4);               // [4, 4, 4]
[1, 2, 3].fill(4, 1);            // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5);         // [1, 2, 3]
Array(3).fill(4);                // [4, 4, 4]
[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}

// Objects by reference.
const arr = Array(3).fill({}) // [{}, {}, {}];
// 需要注意如果 fill 的参数为引用类型,会导致都执行同一个引用类型
// 如 arr[0] === arr[1] 为 true
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

对数组进行筛选

filter方法

filter() 为数组中的每个元素调用一次 callbackFn 函数,并利用所有使得 callbackFn 返回 true 或等价于 true 的值的元素创建一个新数组。callbackFn 只会在已经赋值的索引上被调用,对于那些已经被删除或者从未被赋值的索引不会被调用。那些没有通过 callbackFn 测试的元素会被跳过,不会被包含在新数组中。返回一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组

语法

  1. 箭头函数、
    • filter((element) => { /* … */ } )
    • filter((element, index) => { /* … */ } )
    • filter((element, index, array) => { /* … */ } )

element:数组中当前正在处理的元素。
index:正在处理的元素在数组中的索引。
array:调用了 filter() 的数组本身。

filter() 遍历的元素范围在第一次调用 callbackFn 之前就已经确定了。修改已经访问过的或在确定的范围之外创建的元素,将不会被 callbackFn 访问。如果以相同的方式删除数组中的现有元素,则不会访问它们。

//将数组中大于10 的数组取出,组成一个新的数组返回
function isBigEnough(value) {
  return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

数组的查找方法

find方法

find() 方法:返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。函数会为数组中的每个索引调用即从 0 到 length - 1,而不仅仅是那些被赋值的索引,这意味着对于稀疏数组来说,该方法的效率要低于那些只遍历有值的索引的方法。

语法:

  • find((element) => { /* … */ } )
  • find((element, index) => { /* … */ } )
  • find((element, index, array) => { /* … */ } )

element:当前遍历到的元素。
index:当前遍历到的索引。
array:数组本身。

//查找数组数组对象里包含某个特定值的对象
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 }

findIndex方法

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

语法:

  • findIndex((element) => { /* … */ } )
  • findIndex((element, index) => { /* … */ } )
  • findIndex((element, index, array) => { /* … */ } )

element:当前遍历到的元素。
index:当前遍历到的索引。
array:数组本身。

//查找数组中素数的元素的索引(如果不存在素数,则返回-1)
function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2

findLast方法

findLast() 方法返回数组中满足提供的测试函数条件的最后一个元素的值。如果没有找到对应元素,则返回 undefined。findLast() 方法对数组每一个元素按降序(索引从大到小)执行 callbackFn 函数。

findLast() 方法仍然会访问已删除的元素。
语法:

  • findLast((element) => { /* … */ } )
  • findLast((element, index) => { /* … */ } )
  • findLast((element, index, array) => { /* … */ } )

element:当前遍历到的元素。
index:当前遍历到的索引。
array:数组本身。

//查找在数组对象中 quantity小于2的倒数第一个值。
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 }

findLastIndex方法

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

findLastIndex() 方法仍然会访问已删除的元素。

语法:

  • findLastIndex((element) => { /* … */ } )
  • findLastIndex((element, index) => { /* … */ } )
  • findLastIndex((element, index, array) => { /* … */ } )

element:当前遍历到的元素。
index:当前遍历到的索引。
array:数组本身。

const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];
const index = fruits.findLastIndex(fruit => fruit === "blueberries");
console.log(index); // 3
console.log(fruits[index]); // blueberries

indexOf方法

indexOf() 方法返回在数组中可以找到给定元素的第一个索引,如果不存在,则返回 -1。

语法:

  • indexOf(searchElement)
  • indexOf(searchElement, fromIndex)

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

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

对数组进行判断

isArray方法

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

语法:

  • Array.isArray(value)

value:需要检测的值。

Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar');   // false
Array.isArray(undefined);  // false

// 下面的函数调用都返回 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 });

获取数组的索引

keys方法

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

语法:

  • keys()
var arr = ["a", , "c"];
var sparseKeys = Object.keys(arr);
var denseKeys = [...arr.keys()];
console.log(sparseKeys); // ['0', '2']
console.log(denseKeys);  // [0, 1, 2]

lastIndexOf方法

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

语法:

  • lastIndexOf(searchElement)
  • lastIndexOf(searchElement, fromIndex)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zayyo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值