JavaScript中Array的优化用法

1、使用 Array.includes 代替 Array.indexOf

a = [1,2,3]

a.includes(2)    // true

a.indexOf(2)     // 1

2、使用 Array.find 代替 Array.filter

a = [1,2,3,4]

a.find(x => x>2)       // 3     find返回满足条件的第一个元素

a.filter(x => x>2)     // [3,4]    filter返回满足条件的所有元素

3、使用Array.some 代替 Array.find

a = [1,2,3,4]

a.some(x => x>3)    // true   返回是否存在满足条件的元素

a.find(x => x>3)    // 4      返回满足条件的第一个元素

 

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务