当前位置:网站首页>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
边栏推荐
猜你喜欢
备战金九银十,如何顺利通过互联网大厂Android的笔面试?
万字逐行解析与实现Transformer,并进行德译英实战(一)
(2022牛客多校四)A-Task Computing (排序+动态规划)
pytorch、tensorflow对比学习—功能组件(优化器、评估指标、Module管理)
Robot_Framework:常用内置关键字
MySQL-数据定义语言-DDLdatebase define language
可持久化线段树
Qt Widget 项目对qml的加载实例
pytroch、tensorflow对比学习—搭建模型范式(低阶、中阶、高阶API示例)
The solution to the inconsistency between the PaddleX deployment inference model and the GUI interface test results
随机推荐
Selenium: browser operation
Robot_Framework: Assertion
Asynchronous reading and writing of files
LeetCode 27. 移除元素
pytroch、tensorflow对比学习—搭建模型范式(低阶、中阶、高阶API示例)
万字逐行解析与实现Transformer,并进行德译英实战(一)
对话MySQL之父:一个优秀程序员可抵5个普通程序员
Induction jian hai JustFE 2022/07/29 team, I learned the efficient development summary (years)
USB3.0:VL817Q7-C0的LAYOUT指南(三)
2022.7.27好题选讲
Robot_Framework:常用内置关键字
The sword refers to Offer 68 - I. Nearest Common Ancestor of Binary Search Trees
MySQL实践总结-
可持久化线段树
After the image is updated, Glide loading is still the original image problem
Selenium: Element wait
Malicious attacks on mobile applications surge by 500%
Selenium:弹窗处理
(2022 Nioke Duo School IV) H-Wall Builder II (Thinking)
matplotlib pyplot