[随笔] js数组中 some 、findIndex 和 filter方法 您所在的位置:网站首页 js获取数组下标的方法 [随笔] js数组中 some 、findIndex 和 filter方法

[随笔] js数组中 some 、findIndex 和 filter方法

2024-03-05 17:10| 来源: 网络整理| 查看: 265

Array.some(callback) some会遍历数组中的每个元素,让每个值都执行一遍callback函数如果有一个元素满足条件,返回true , 剩余的元素不会再执行检测。如果没有满足条件的元素,则返回false。可以用来对 索引 进行操作

注意:

some() 不会对空数组进行检测。some() 不会改变原始数组。示例: var flag = this.books.some(item=>{ return this.id == item.id; })

上面的代码的注意点–-this的指向问题:

上面的函数用的是es6的箭头函数,箭头函数的this指向的是当前作用域;如果使用function那么this指向的是window;这个方法最终的返回值是true|false

source: https://blog.csdn.net/poppy995/article/details/95210596

Array.findIndex(callback)

findIndex方法,用来快速寻找索引值,下面简单介绍其用法

findIndex会遍历数组中的每个元素,让每个值都执行一遍测试条件(函数)当数组中的元素在测试条件时返回 true 时, findIndex() 方法返回符合条件的元素的索引位置,之后的值不会再调用执行函数。如果没有符合条件的元素返回 -1可以用来快速寻找索引 ,需要先使用":key=id"绑定索引。

注意:

findIndex() 不会对空数组进行检测,不执行。findIndex() 不会改变原始数组。 示例: var index = this.list.findIndex(item => { if(item.id == id) { return true; } })

source: https://www.runoob.com/jsref/jsref-findindex.html

Array.filter(callback(v))

filter方法: ①filter方法可以遍历数组 ②filter方法的参数是函数 ③filter方法函数有形参v ④形参v指的是数组中每个元素 ⑤filter方法中函数有返回值(把符合条件的元素放在一个新数组中返回) 示例:

const arr = [1,2,3].filter((v)= > { console.log(v); //输出为1,2,3 return v>1; }) console.log(arr); //输出为[2,3];

source: https://blog.csdn.net/AirrrNinety9/article/details/89311327



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有