当前位置:网站首页>Talk about the bugs in using for in to traverse the array in js
Talk about the bugs in using for in to traverse the array in js
2022-08-01 05:22:00 【Elegant Roasted Sweet Potatoes】
*****For in array traversal pit*****
Using for in traversal on an array, we will encounter a very serious bug, that is, for in will traverse the properties added to the prototype chain of the array, that is to say, the for-in loop body acting on the arrayIn addition to traversing array elements, custom properties are also traversed.
1. When we use for in to traverse the array
Array.prototype.istrue = function(value) {return true;}
var a = [1,2];
for(var i in a) {
console.log(a[i]);
}
Output:
1
2
function(value) {return true;}
Therefore, it is not recommended to use for in in array traversal, but use forEach or for of instead, because forEach can only traverse index arrays, while for of can traverse everything with numerical subscripts, that is, index arrays, array-like objects,String, so we generally recommend to use for of instead of forEach and for in to traverse the array.Note: The i variable above is a string, not a number
2. Generally, we usually use for in to traverse objects
var a = {"x":1,"y":2};
for(var i in a) {
console.log(a[i]);}
Output:
1
2
3. If you use for in to traverse the array, use hasOwnProperty to avoid traversing properties or methods on the prototype chain
Array.prototype.istrue = function(value) {return true;}
var a = [1,2];
for(var i in a) {
if(a.hasOwnProperty(i){
console.log(a[i]);
})
}
Output:
1
2
边栏推荐
- pytorch、tensorflow对比学习—功能组件(激活函数、模型层、损失函数)
- 冲刺金九银十,Android开发面试(内含面试资料|面试题|源码)
- WebSocket实现聊天功能
- Robot growth in China
- Swastika line-by-line parsing and realization of the Transformer, and German translation practice (a)
- Causes and solutions of lock table
- Selenium: Introduction
- y83.第四章 Prometheus大厂监控体系及实战 -- prometheus告警机制进阶(十四)
- 第6章——数据库的安全性
- 微信小程序接口调用凭证(获取token)auth.getAccessToken接口开发
猜你喜欢

Robot_Framework: commonly used built-in keywords

y83.第四章 Prometheus大厂监控体系及实战 -- prometheus告警机制进阶(十四)

从离线到实时对客,湖仓一体释放全量数据价值

WebSocket实现聊天功能

Selenium: Popup Handling

2022.7.26 Mock Competition

pytroch、tensorflow对比学习—功能组件(数据管道、回调函数、特征列处理)

pytroch、tensorflow对比学习—专栏介绍

冲刺金九银十,Android开发面试(内含面试资料|面试题|源码)

(2022 Nioke Duo School IV) H-Wall Builder II (Thinking)
随机推荐
数据湖:数据同步工具NiFi
Selenium: Element wait
(2022牛客多校四)H-Wall Builder II(思维)
WPF入门项目必知必会-初步了解数据绑定 binding
Selenium:下拉框操作
AspNet.WebApi.Owin custom Token request parameters
state compressed dp
图片更新之后Glide加载依旧是原来的图片问题
Selenium:元素判断
关于给Qt做一个软件初始化的进度条
备战金九银十,如何顺利通过互联网大厂Android的笔面试?
PAT乙级 1002 写出这个数
Hunan institute of technology in 2022 ACM training sixth week antithesis
ORACLE 实现另外一个用户修改包(package)
Selenium: Introduction
pytorch、tensorflow对比学习—张量
AspNet.WebApi.Owin 自定义Token请求参数
uva12326
Robot_Framework: Assertion
A,H,K,N