当前位置:网站首页>说说js中使用for in遍历数组存在的bug
说说js中使用for in遍历数组存在的bug
2022-08-01 05:18:00 【儒雅的烤地瓜】
*****for in数组遍历的坑*****
对数组使⽤for in遍历,我们会遇到⼀个很严重的bug,那就是for in会遍历到数组添加到原型链上的属性,也就是说作用于数组的for-in循环体除了遍历数组元素外,还会遍历自定义的属性。
1. 当我们对数组使用for in遍历时
Array.prototype.istrue = function(value) {return true;}
var a = [1,2];
for(var i in a) {
console.log(a[i]);
}
输出结果:
1
2
function(value) {return true;}
所以,数组的遍历中不推荐使用for in,而使用forEach或是for of代替,由于forEach只能遍历索引数组,而for of能遍历数字下标的一切,即索引数组、类数组对象、字符串,所以我们⼀般遍历数组推荐使用for of代替forEach、for in。注:上⾯的i变量是string,并不是number
2. ⼀般的,我们对对象的遍历通常使用for in
var a = {"x":1,"y":2};
for(var i in a) {
console.log(a[i]);}
输出结果:
1
2
3. 如果使⽤了for in遍历数组,就⽤hasOwnProperty来规避遍历到原型链上的属性或⽅法
Array.prototype.istrue = function(value) {return true;}
var a = [1,2];
for(var i in a) {
if(a.hasOwnProperty(i){
console.log(a[i]);
})
}
输出结果:
1
2
边栏推荐
- Li Chi's work and life summary in July 2022
- Use controls as brushes to get bitmap code records
- Selenium:操作Cookie
- ModuleNotFoundError: No module named ‘tensorflow.keras‘报错信息的解决方法
- 可持久化线段树
- Selenium: Element wait
- I met a shell script
- Selenium:元素定位
- 25. Have you been asked these three common interview questions?
- Selenium:上传、下载文件
猜你喜欢
Swastika line-by-line parsing and realization of the Transformer, and German translation practice (a)
Logitech Mouse Experience Record
初识shell脚本
Robot_Framework:关键字
USB3.0:VL817Q7-C0的LAYOUT指南(三)
华为Android开发面试后得出的面试秘诀
中国的机器人增长
(2022牛客多校四)N-Particle Arts(思维)
Lawyer Interpretation | Guns or Roses?Talking about Metaverse Interoperability from the Battle of Big Manufacturers
state compressed dp
随机推荐
(2022牛客多校四)K-NIO‘s Sword(思维)
WPF项目-初步了解数据绑定 binding
JWL-11/2-99.9A电流继电器
备战金九银十,如何顺利通过互联网大厂Android的笔面试?
AspNet.WebApi.Owin 自定义Token请求参数
MySQL-DML language-database operation language-insert-update-delete-truncate
Typescript22 - interface inheritance
(more than 2022 cattle school four) A - Task Computing + dynamic programming (sort)
Asynchronous reading and writing of files
可视化全链路日志追踪
II. Binary tree to Offer 68 - recent common ancestor
NDK does not contain any platforms问题解决
Swastika line-by-line parsing and realization of the Transformer, and German translation practice (2)
微信小程序接口调用凭证(获取token)auth.getAccessToken接口开发
Selenium:下拉框操作
微信小程序获取手机号phonenumber.getPhoneNumber接口开发
pytroch、tensorflow对比学习—功能组件(数据管道、回调函数、特征列处理)
Selenium: Element wait
类神经网络训练不起来怎么办
万字逐行解析与实现Transformer,并进行德译英实战(二)