数组的遍历(元素的筛选)-使用方法 原理 | find/findLast findIndex/findLastIndex reduce every forEach some filter map

ES6 数组的遍历(元素的筛选)

参考文章

这些方法的参数是一个回调函数functon(value,index,arr)

  • value:当前遍历的元素
  • index:当前遍历的元素下标
  • arr:当前遍历的数组

总结

  • 特定的循环,需要中断和跳过可使用for
  • 无需返回值可使用 forEachfor...of
  • 检查是否满足指定条件而无需使用元素可使用someevery
  • 筛选符合条件的元素可使用filterfindfindLast
  • 找到符合条件的元素索引可使用 findIndexfindLastIndex
  • 需要对不符合展示条件的数据继续再处理时可使用map
  • 需要依赖数组元素上次结果,如累计可使用reducereduceRight

find(callback)寻找第一个满足条件的元素/findLast寻找最后一个满足条件的元素

数组实例方法find(function):遍历数组,查找数组中符合条件的第一个元素,立即返回该元素的值。如果没有找到,则返回undefined

数组实例方法findLast(function):从后往前遍历,寻找最后一个满足条件的元素

callback返回布尔值,true表示找到了

案例

const arr = [
  {
    
     id: 1, name: 'Alice' },
  {
    
     id: 2, name: 'Bob' },
  {
    
     id: 3, name: 'Charlie' }
];
const targetId = 2;
const targetObj = arr.find(obj => obj.id === targetId);// { id: 2, name: 'Bob' },

实现原理

//调用时通过数组实例.find调用,所以this指向调用的数组实例
Array.prototype.find = function(fn) {
    
    
    for (let i = 0; i < this.length; i++) {
    
    
        if (fn(this[i],i)) return this[i]
        //this指向调用的数组,i表示数组的下表,this[i]代表依次去数组元素
    }
}

findIndex(callback)寻找第一个满足条件的元素下标/findLastIndex(callback)

数组实例方法find(callback):遍历数组,查找数组中符合条件的第一个元素,立即返回该元素的下标。如果没有找到,则返回-1。

数组实例方法findLastIndex(callback):从右往左遍历,寻找数组中最后一个满足条件的元素

callback返回布尔值,true表示找到了

使用场景

  • 数组中的元素是值类型: arr.indexOf()
  • 数组中的元素是引用类型: arr.findIndex()

案例

const arr = [
  {
    
     id: 1, name: 'Alice' },
  {
    
     id: 2, name: 'Bob' },
  {
    
     id: 3, name: 'Charlie' }
];
const targetId = 2;
const targetObj = arr.findIndex(obj => obj.id === targetId); //1

实现原理

Array.prototype.find = function(fn) {
    
    
	for(let i=0;i<this.length;i++){
    
    
		if(fn(this[i],i)){
    
    
			  return i;
		}
	}
}

map(callback)映射数组

数组实例方法map(callback):将原数组的每一个元素进行映射,返回一个新数组。

数组实例方法callback返回映射后的元素

说明

  • 映射之后一定要将映射后的元素返回,也就是参数函数一定要有返回值,不然返回undefined
  • 不会影响原数组,只是将原来的数组拷贝了一份,把拷贝的数组项进行更改,支持链式调用

案例

const arr = [
  {
    
     id: 1, name: 'Alice' },
  {
    
     id: 2, name: 'Bob' },
  {
    
     id: 3, name: 'Charlie' }
];
const targetId = 2;
const targetObj = arr.map(obj => obj.id++);

实现原理

Array.prototype.map = function (callback){
    
    
	const newArr= [];
	for(let i =0;i<this.length;i++){
    
    
		newArr.push(callback&&callback(this[i]))
	}
	return newArr;
}

filter(callback)筛选数组

数组实例方法filter(callback):根据条件筛选数组,将符合条件的元素放入新数组中,返回新数组。

数组实例方法callback返回布尔值,结果为true的元素放入新数组中

案例:去重

const arr = [1, 2, 2, 3, 4, 5, 5, 6, 7, 7,8,8,0,8,6,3,4,56,2];
const arr2 = arr.filter((x, index,self)=>self.indexOf(x)===index)
console.log(arr2); //[1, 2, 3, 4, 5, 6, 7, 8, 0, 56]

实现原理

Array.prototype.filter = function (callback) {
    
    
	const newArr = [];
	for(let i=0;i<this.length;i++){
    
    
		if(callback(this[i]))newArr.push(this[i])
	}
	return newArr;
}

reduce(callback,intialValue)累加器/reduceRight从后往前

数组实例方法 reduce(callback,intialValue)相当于数组的累加器,常用于条件统计。比如统计数组中大于20的元素个数,返回累计值。

数组实例方法reduceRight(callback,intialValue)类似 reduce(callback,intialValue),遍历顺序从右到左,使用场景:字符串的反转等。

callback(accumulator,currentValue,[index],[array])回调函数的参数

  • accumulator 累计器的值,是上一次调用回调时返回的累计值或者是初始值intialValue
  • currentValue 当前元素
  • index 当前元素下标
  • array 当前数组
  • callback函数的返回值就是当前函数执行结束后的累计值

案例

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((prev, curr) => prev + curr, 0);
console.log(sum); // 15

实现原理

Array.prototype.reduce= function (callback,initVal) {
    
    
	const res = initVal;
	for(let i=0;i<this.length;i++){
    
    
		res = callback(res ,this[i],i,this)//累计值
	}
	return res ;
}

some(callback)判断该数组是否存在符合条件的元素

数组实例方法some(callback):判断数组中是否存在符合条件的元素,如果数组中有一个元素满足条件,立即返回true , 剩余的元素不会再执行检测。如果全部都不符合,返回false返回布尔值

callback返回布尔值,true表示找到了符合条件的元素,循环结束直接返回true

经典场景 : 非空判断。 多个表单只要有一个是空的,就不能提交

const arr = [1, 2, 3, 4, 5];
const result = arr.some(item => item > 3);
console.log(result); // true

实现原理

Array.prototype.some= function(callback){
    
    
	for(let i=0;i<this.length;i++){
    
    
		if(callback(this[i]))return true
	}
	return false;
}

every(callback):判断该该数组是否每一个元素都符合条件

数组实例方法every(callback):判断数组中是否每一个元素都符合条件,如果是返回true

callback返回布尔值,true表示当前元素符合条件。false表示当前元素不符合条件,循环结束,返回false

案例

let arr = [1,2,3,4];
let res = arr.every(item => item > 0)
console.log(res);   // true

实现原理

Array.prototype.some= function(callback){
    
    
	for(let i=0;i<this.length;i++){
    
    
		if(!callback(this[i]))return false
	}
	return true;
}

forEach(callback)循环修改旧数组

数组实例方法forEach(callback)循环数组, 用于对数组中的每个元素执行指定的操作。

特点

  • 不返回新数组,会修改旧数组
  • 不能break终止和continue 进入下一个循环,除非抛出异常
  • 使用 return 时,效果和在 for 循环中使用 continue 一致
  • 对空数组不执行回调

形参item采用赋值的形式

// 不可以直接修改元素,但是可以修改元素的属性- 形参是赋值形式
numbers.forEach((item, index, arr) => {
    
    
    item = item * 2; // 这里只是修改了形参item的值,并不会修改原数组
    arr[index] = item * 2; // 通过修改属性修改原数组值
})

猜你喜欢

转载自blog.csdn.net/qq_41370833/article/details/131790323
今日推荐