当前位置: 首页 > news >正文

【JavaScript-基础】map、forEach、for、for in、for of等的区别

tips:循环虽好,大家都得按自己所需场景进行使用。个人建议,不喜勿喷

forEach

forEach: forEach(item,index,array), item:当前处理的数据,index:下标,
array:整个数组
遍历全部数据,不能通过return结束循环,消耗性能
用于不转换数据的全部遍历。
tips: 除了抛出异常以外,没有办法中止或跳出 forEach() 循环。如果你需要中止或跳出循环,forEach() 方法不是应当使用的工具。

 // forEach 跳出循环const inventory = [{ name: "apples", quantity: 2 },{ name: "bananas", quantity: 0 },{ name: "cherries", quantity: 5 },];function  fn(arr){console.log('回调函数',arr)}function getItem(arr,name,fn){let item = nulltry {arr.forEach((element,i,arr) => {console.log(element,i,arr)if(element.name === name){item = element;fn(arr)throw Error();}});} catch (error) {}return item;}// forEach 和 map 的原生实现,都可挂载Array的原型上去实现你想要的方法
Array.prototype.myForEach = function (fn) {for(let i = 0; i < this.length; i++){fn(this[i], i, this);}
};
arr.myForEach(function (currentValue, currentIndex, currentArray) {console.log(currentValue, currentIndex, currentArray);
});
// map 和这个类似

Map

map(item,index,array), item:当前处理的数据,index:下标,
array:整个数组
一定遍历全部数据,不能通过return结束,消耗性能,不要常用。
常用于转换数据结构,比forEach快。和forEach都不影响原有的数组结构。

 const inventory = [{ name: "apples", quantity: 2 },{ name: "bananas", quantity: 0 },{ name: "cherries", quantity: 5 },];const newarr = inventory.map(({ name, quantity }) => ({[name]: quantity,}));

for...of

一般的对象是不能使用for...of 进行遍历。具有 iterator 接口就可以用for...of循环遍历它的成员(属性值value)for...of循环可以使用的范围包括数组、Set 和 Map 结构、某些类似数组的对象、Generator 对象,以及字符串。for...of循环调用遍历器接口,数组的遍历器接口只返回具有数字索引的属性。对于普通的对象,for...of结构不能直接使用,会报错,必须部署了 Iterator 接口后才能使用。可以中断循环。****

一个对象如果要具备可被 for...of 循环调用的 Iterator 接口,就必须在其 Symbol.iterator 的属性上部署遍历器生成方法(或者原型链上的对象具有该方法)

tips: 遍历器对象根本特征就是具有next方法。每次调用next方法,都会返回一个代表当前成员的信息对象,具有value和done两个属性。

实例代码如下:
普通对象是不具备遍历器接口,例如:

 let obj = {name:'jack',age:20,job:'web engineer'
}for(const item of obj){console.log(item) //Uncaught TypeError: obj is not iterable
}

给普通对象增加Iterator 才能进行遍历:
想了解为啥要这么使用点击该链接

let obj = {name:'jack',age:20,job:'web engineer',[Symbol.iterator](){const self = this;const keys = Object.keys(self);let index = 0;return{next(){if(index < keys.length){return {value:self[keys[index++]],done:false}}else{return {value:undefined,done:true}}}}}}for(const item of obj){console.log(item) //name:'jack',//age:20,//job:'web engineer'}

注意:
原生具备 Iterator 接口的数据结构有:

  • Array
  • Map
  • Set
  • String
  • TypedArray
  • 函数的 arguments 对象
  • NodeList 对象
  • ES6 的数组、Set、Map 都部署了以下三个方法: entries() / keys() / values(),调用后都返回遍历器对象。

for...in

不但可以遍历数组,还可以遍历对象,数组遍历下标,对象遍历属性。
大多场景用来遍历对象。遍历对象自身的和继承的可枚举的属性,也就是说会包括那些原型链上的属性。如果想要仅迭代自身的属性,那么在使用 for...in 的同时还需要配合 getOwnPropertyNames() 或 hasOwnProperty()。可以中断循环。

let obj = {name:'jack',age:20,job:'web engineer',
}
for(const key in obj){console.log(key); // name,age,jobconsole.log(obj[key]) // jack,20,web engineer
}let arr1 = ['name','age','job']
for(const key in arr1){console.log(key); // 1,2,3console.log(arr1[key]) // name,age,job
}

xdm,再不睡觉头发丝又得掉几根...

http://www.rkmt.cn/news/25921.html

相关文章:

  • dotnet 利用 Windows 注册表实现开机自动启动
  • Python 类属性的应用场景
  • 玄机——第五章 Windows 实战-evtx 文件分析
  • 软件工程第二次团队作业——构建一个智能体
  • CityNav:包含地理信息的语言目标空中导航数据集 - MKT
  • Linux权限维持-后门
  • [Tool] [HTTP] curl 命令行工具:基础与进阶用法
  • sourcetree 克隆项目仓库地址,输入账号密码后提示:这是一个无效的源路径/URL
  • 北航高低无人机协同导航方案:高空掌全局+低空查细节 - MKT
  • 20251020 之所思 - 人生如梦
  • 方格图路径计数 dp 的反射路径优化
  • 企业信息化建设的钱都花在哪儿了?
  • 解释这些区块链核⼼概念:区块、交易、Merkle Tree、共识机制(PoW、PoS)、Gas Fee 原理2
  • 一次XFS死锁问题分析
  • P11150 [THUWC 2018] 字胡串
  • 软工第二次编程作业
  • 20232304 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 20251020周一日记
  • 英语_阅读_Start school_待读
  • 题解:Luogu P10004 [集训队互测 2023] Permutation Counting 2
  • 扣一个细节问题
  • 软工第三次作业————结对作业
  • 题解:Luogu P6898 [ICPC 2014 WF] Metal Processing Plant
  • 题解:Luogu P9260 [PA 2022] Miny
  • 题解:Luogu P13544 [OOI 2022] Serious Business
  • 题解:Luogu P14254 分割(divide)
  • 构造单
  • CSP-S 35
  • CSP-S 31
  • 2025网络安全振兴杯wp