ES5与ES6中数组find、findIndex,数组如何查找

一、ES5中的查找

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

语法:

arr.some(callback(element[, index[, array]])[, thisArg])

callback

用来测试每个元素的函数,接受三个参数:

element

数组中正在处理的元素。

index 可选

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

array可选

some()被调用的数组。

thisArg可选

执行 callback 时使用的 this 值。

返回值

数组中有至少一个元素通过回调函数的测试就会返回true;所有元素都没有通过回调函数的测试返回值才会为false。

例子:

// es5
let arr5 = [4, 10, 2, 30, 1]
let test1 =  arr5.some(function(item){
  return item > 29
})
console.log(test1) // true

// es6
[12, 5, 8, 1, 4].some(x => x > 10); // true

 2.Array.filter()  方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。 

语法:

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

callback

用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数:

element

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

index可选

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

array可选

调用了 filter 的数组本身。

thisArg可选

执行 callback 时,用于 this 的值。

返回值

一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组。

 代码1:

let arr = [1, 2, 3, 4, 5, 6]
let newarr = arr.filter(function(item){
  return item > 3
})
console.log(newarr) //[4,5,6]

代码2:

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

二、ES6的查找做法

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

语法:

arr.find(callback[, thisArg])

callback

在数组每一项上执行的函数,接收 3 个参数:

element

当前遍历到的元素。

index可选

当前遍历到的索引。

array可选

数组本身。

thisArg可选

执行回调时用作this 的对象。

 代码1:

let arr = [1, 2, 3, 4, 5, 6]

let test2 =  arr.find(function(item){
  return item > 4
})
console.log(test2) // 5

说明:find去寻找数组。只要是有符合条件的就返回他的数据

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

语法:

arr.findIndex(callback[, thisArg])

callback

针对数组中的每个元素, 都会执行该回调函数, 执行时会自动传入下面三个参数:

element

当前元素。

index

当前元素的索引。

array

调用findIndex的数组。

thisArg

可选。执行callback时作为this对象的值.

返回值

    数组中通过提供测试函数的第一个元素的索引。否则,返回-1

代码1:

let arr6 = [4, 6, 7, 22, 4, 6]
let newContent = arr6.findIndex(function(item){
  return item > 10
})
console.log(newContent) // 3

说明:返回符合条件的第一个值的索引,上面大于10的第一个数是22,所以22对应的索引值为3

总结:

1.Array.find()和Array.some()类似,都是满足提供的测试函数的第一个元素的值,但是返回值却是不一样的,Array.find()是返回他的数值,没有就返回underfind,而Array.some是返回boolean的,满足一个则返回true,都不满足则返回false

2.Array.find()与Array.filter()比较,Array.find()是满足测试额第一个元素。而Array.filter(),是返回满足条件的所有元素。

发布了62 篇原创文章 · 获赞 11 · 访问量 8630

猜你喜欢

转载自blog.csdn.net/qq_38588845/article/details/103383422
今日推荐