遍历的12种方法-程序员宅基地

技术标签: js  es6  javascript  

关于遍历的12种方法

ES5:
forEach、every 、some、 filter、map、reduce、reduceRight、
ES6:
find、findIndex、keys、values、entries

forEach 按升序为数组中含有效值的每一项执行一次回调函数

array.forEach(function(currentValue, index, arr), thisValue)
关于forEach()
  • 无法中途退出循环,只能用return退出本次回调,进行下一次回调。
  • 它总是返回 undefined值,即使你return了一个值。
eg:
let a = [1, 2, ,3]; // 最后第二个元素是空的,不会遍历(undefined、null会遍历)
let obj = {
     name: 'Avegetable' };
let result = a.forEach(function (value, index, array) {
     
    a[3] = '改变元素';
    a.push('添加到尾端,不会被遍历')
    console.log(value, 'forEach传递的第一个参数'); // 分别打印 1 ,2 ,改变元素
    console.log(this.name); // Avegetable 打印三次 this绑定在obj对象上
    // break; // break会报错
    return value; // return只能结束本次回调 会执行下次回调
    console.log('不会执行,因为return 会执行下一次循环回调')
}, obj);
console.log(result); // 即使return了一个值,也还是返回undefined
// 回调函数也接受接头函数写法

every 检测数组所有元素是否都符合判断条件

array.every(function(currentValue, index, arr), thisValue)
关于every()
  • 如果数组中检测到有一个元素不满足,则整个表达式返回 false,且剩余的元素不会再进行检测。
  • 如果所有元素都满足条件,则返回 true。
eg:
function isBigEnough(element, index, array) {
     
    return element >= 10; // 判断数组中的所有元素是否都大于10
}
let result = [12, 5, 8, 130, 44].every(isBigEnough);   // false
let result = [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

some 数组中的是否有满足判断条件的元素

array.some(function(currentValue, index, arr), thisValue)
关于some()
  • 如果有一个元素满足条件,则表达式返回true, 剩余的元素不会再执行检测。
  • 如果没有满足条件的元素,则返回false。
eg:
function isBigEnough(element, index, array) {
    
    return (element >= 10); //数组中是否有一个元素大于 10
}
let result = [2, 5, 8, 1, 4].some(isBigEnough); // false
let result = [12, 5, 8, 1, 4].some(isBigEnough); // true

filter 过滤原始数组,返回一个新数组, 其包含通过所提供函数实现的测试的所有元素

let new_array = arr.filter(function(currentValue, index, arr), thisArg)
eg:
let a = [32, 33, 16, 40];
let result = a.filter(function (value, index, array) {
    
    return value >= 18; // 返回a数组中所有大于18的元素
});
console.log(result,a);// [32,33,40] [32,33,16,40]

map 创建一个新数组,结果是该数组中的每个元素都调用一个提供的函数后返回的结果

let new_array = arr.map(function(currentValue, index, arr), thisArg)
eg:
let a = ['1','2','3','4'];
let result = a.map(function (value, index, array) {
    
return value + '新数组的新元素'
});
console.log(result, a); 
// ["1新数组的新元素","2新数组的新元素","3新数组的新元素","4新数组的新元素"] ["1","2","3","4"]

reduce 对累加器和数组中的每个元素(从左到右)应用一个函数,最终合并为一个值。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

参数:

  • total(必须),初始值, 或者上一次调用回调返回的值
  • currentValue(必须),数组当前元素的值
  • index(可选), 当前元素的索引值
  • arr(可选),数组对象本身
  • initialValue(可选): 指定第一次回调 的第一个参数

回调第一次执行时:

  • 如果 initialValue 在调用 reduce 时被提供,那么第一个 total 将等于 initialValue,此时 currentValue 等于数组中的第一个值;
  • 如果 initialValue 未被提供,那么 total 等于数组中的第一个值,currentValue 等于数组中的第二个值。此时如果数组为空,那么将抛出 TypeError
  • 如果数组仅有一个元素,并且没有提供 initialValue,或提供了 initialValue 但数组为空,那么回调不会被执行,数组的唯一值将被返回。
eg:
// 数组求和 
let sum = [0, 1, 2, 3].reduce(function (a, b) {
    
    return a + b;
}, 0);
// 6
// 将二维数组转化为一维 将数组元素展开
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
    (a, b) => a.concat(b),
    []
);
// [0, 1, 2, 3, 4, 5]

reduceRight 方法除了与reduce执行方向相反外,其他完全与其一致。

find 用于找出第一个符合条件的数组成员,并返回该成员,如果没有符合条件的成员,则返回undefined。

let item = arr.find(function(currentValue, index, arr), thisArg)
eg:
let a = [1, 4, -5, 10].find((n) => n < 0); // 返回元素-5
let b = [1, 4, -5, 10,NaN].find((n) => Object.is(NaN, n));  // 返回元素NaN

findIndex 返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

let index = arr.findIndex(function(currentValue, index, arr), thisArg)
eg:
let a = [1, 4, -5, 10].findIndex((n) => n < 0); // 返回索引2
let b = [1, 4, -5, 10,NaN].findIndex((n) => Object.is(NaN, n));  // 返回索引4

keys(),values(),entries() 遍历键名、遍历键值、遍历键名+键值。三个方法都返回一个新的 Array Iterator 对象,对象根据方法不同包含不同的值。

array.keys()
array.values()
array.entries()
eg:
for (let index of ['a', 'b'].keys()) {
    
    console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
    
    console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
    
    console.log(index, elem);
}
// 0 "a"
// 1 "b"
  • for..of中如果遍历中途要退出,可以使用break退出循环。

  • 如果不使用for...of循环,可以手动调用遍历器对象的next方法,进行遍历

let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_45374947/article/details/107311137

智能推荐

bboss persistent事务管理介绍 (二)-程序员宅基地

文章浏览阅读126次。4.9.5 事务管理的相关接口事务管理器:com.frameworkset.orm.transaction.TransactionManager ,每个接口表:名称功能描述说明&nbsp;&nbsp;public void begin() throws TransactionException..._bptransactionmanager

Android studio gradlew 使用方法_android studio gradlew-程序员宅基地

文章浏览阅读4.1k次。Android studio gradlew 使用方法./gradlew clean clean项目./gradlew build 构建项目./gradlew assembleDebug or /gradlew aD 编译并打Debug包./gradlew assembleRelease or /gradlew aR 编译并打Release的包./gradlew installRelease or /gradlew iR Release模式打包并安装./gradlew installDebu_android studio gradlew

COCO数据集的标注格式_refcoco数据集-程序员宅基地

文章浏览阅读2.6w次,点赞19次,收藏51次。COCO数据集的标注格式COCO的 全称是Common Objects in COntext,是微软团队提供的一个可以用来进行图像识别的数据集。MS COCO数据集中的图像分为训练、验证和测试集。COCO通过在Flickr上搜索80个对象类别和各种场景类型来收集图像,其使用了亚马逊的Mechanical Turk(AMT)。比如标注image captions(看图说话)这_refcoco数据集

2.08 hyperledger fabric完整案例_hyperledger fabric 项目实例-程序员宅基地

文章浏览阅读3.1k次。1.fabric开发流程需求整理合约编写合约部署合约交互外部服务编写2.需求分析开发一个资产转让功能模块平台功能 用户开户和销户 资产登记,解决资产上链和用户绑定资产 资产转让,资产所有权的变更 查询功能,用户查询、资产查询、资产变更历史查询3.合约编写assetsExchange.go4.合约部署关闭docker生成通道的创世交易查看..._hyperledger fabric 项目实例

VC++实现获取本地主机网卡信息_vc 网卡名-程序员宅基地

文章浏览阅读4.3k次,点赞2次,收藏4次。我们在进行网络编程的时候,经常需要获取本地主机,网卡的信息,我们代码实现如下。#include "../common/initsock.h"#include #include #include #include "protoutils.h"#include "ProtoPacket.h"#pragma comment(lib, "Iphlpapi.lib")DWORD W_vc 网卡名

Wireshark的学习与使用_line-based text data-程序员宅基地

文章浏览阅读1.1k次。目录前言1.简介和基础流量分析是什么?HTTP协议和TCP协议2.Wireshark 流量分析中的王者Wireshark是什么Wireshark基本使用方法数据包筛选数据包搜索数据包还原数据提取流量包的修复3.Web流量包的分析4.USB流量包的分析5.ICMP流量包的分析前言本篇文章是基于B站视频 CTF MISC杂项流量分析专题培训1 做的学习笔记,如有写得不到位的地方请多多指教~ ∠(°ゝ°)敬礼1.简介和基础流量..._line-based text data

随便推点

计算机专业教授推荐信,计算机系教授推荐信样本-程序员宅基地

文章浏览阅读52次。At the request of Mr. Xizhen Chen, my former student in the Department of Computer Science, Beijing Univ. of Sciences, I am glad to write this letter furnishing my evaluation of his academic aptitude ...

Ubuntu使用记录_ubuntu系统安装 xmltodict-程序员宅基地

文章浏览阅读1k次。ubuntu使用_ubuntu系统安装 xmltodict

如何在Qt中使用boost库_qt使用boost-程序员宅基地

文章浏览阅读1.4w次,点赞13次,收藏42次。如何在Qt中使用boost库、c++11 using 类型别名用法、c++11 auto 关键字类型推导_qt使用boost

Linux /etc目录详解-程序员宅基地

文章浏览阅读509次。Linux /etc目录详解 /etc目录   包含很多文件.许多网络配置文件也在/etc 中. /etc/rc or/etc/rc.d or/etc/rc*.d   启动、或改变运行级时运行的scripts或scripts的目录. /etc/passwd   用户数据库,其中的域给出了用户名、真实姓名、家目录、加密的口令和用户的其他信息. /etc/fdprm   软..._/etc/*{thomas,rbd}

这 3 个 Set 集合的实现有点简单,那来做个总结吧_pk53com-程序员宅基地

文章浏览阅读2.6k次。Set 接口是 Java Collections Framework 中的一员,它的特点是:不能包含重复的元素,允许且最多只有一个 null 元素。Java 中有三个常用的 Set 实现类:HashSet: 将元素存储在哈希表中,性能最佳,但不能保证元素的迭代顺序LinkedHashSet: 维护一个链表贯穿所有元素,按插入顺序对元素进行迭代TreeSet: 将元素存储在一个红黑树中,按元素大小排序的序列迭代JDK 在实现时,这 3 个 Set 集合的核心功能其实分别委托给了: HashMap, L_pk53com

mysql连接数过多解决方案-程序员宅基地

文章浏览阅读595次。mysql 默认链接数是100个最大是16384。原则:想尽一切办法不重启导致原因:出现这种错误明显就是 mysql_connect 之后忘记 mysql_close;当大量的connect之后,就会出现Too many connections的错误,mysql默认的连接为100个,而什么情况下会出现这种错误呢?正常的mysql_connect 之后调用 mysql..._mysql connections数量很大怎么办