当前位置:网站首页>说说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
边栏推荐
- UE4 rays flashed from mouse position detection
- 【MySQL必知必会】 表的优化 | 充分利用系统资源
- pytorch、tensorflow对比学习—功能组件(优化器、评估指标、Module管理)
- 万字逐行解析与实现Transformer,并进行德译英实战(三)
- PaddleX部署推理模型和GUI界面测试结果不一致的解决方法
- The solution to the inconsistency between the PaddleX deployment inference model and the GUI interface test results
- leetcode125 验证回文串
- 混合型界面:对话式UI的未来
- MySQL-Data Definition Language-DDLdatebase define language
- Robot_Framework: keyword
猜你喜欢

MySQL-数据操作-分组查询-连接查询-子查询-分页查询-联合查询

II. Binary tree to Offer 68 - recent common ancestor

Code Interview Guide for Programmers CD15 Generating an Array of Windowed Maximums

(2022 Nioke Duo School IV) H-Wall Builder II (Thinking)

(2022 Niu Ke Duo School IV) K-NIO's Sword (Thinking)

High Numbers | 【Re-integration】Line Area Score 880 Examples

Pyspark Machine Learning: Vectors and Common Operations
![[target detection] YOLOv7 theoretical introduction + practical test](/img/ff/a83acbf9dd5cc2f907f3538d287842.png)
[target detection] YOLOv7 theoretical introduction + practical test

2022年湖南工学院ACM集训第六次周测题解

leetcode125 验证回文串
随机推荐
中国的机器人增长
将CSV文件快速导入MySQL中
LeetCode 231. 2 的幂
Li Chi's work and life summary in July 2022
matplotlib pyplot
Qt Widget 项目对qml的加载实例
ModuleNotFoundError: No module named 'tensorflow.keras' error message solution
pytroch、tensorflow对比学习—使用GPU训练模型
Power button (LeetCode) 212. The word search II (2022.07.31)
Swastika line-by-line parsing and realization of the Transformer, and German translation practice (a)
微信小程序接口调用凭证(获取token)auth.getAccessToken接口开发
移动应用恶意攻击激增500% 三六零天御为APP免费构建安全屏障
剑指 Offer 68 - II. 二叉树的最近公共祖先
LeetCode 1189. “气球” 的最大数量
Check控件
2022年超全的Android面经(附含面试题|进阶资料)
About making a progress bar for software initialization for Qt
Selenium: Dropdown Box Actions
对话MySQL之父:一个优秀程序员可抵5个普通程序员
2022.7.26 模拟赛