当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
图片更新之后Glide加载依旧是原来的图片问题
Selenium: Dropdown Box Actions
程序员代码面试指南 CD15 生成窗口最大值数组
JWL-11/2-99.9A电流继电器
MySQL-DML语言-数据库操作语言-insert-update-delete-truncate
Selenium: element positioning
Qt Widget 项目对qml的加载实例
Selenium: form switching
Jupyter shortcuts
ApiFile
冲刺金九银十,Android开发面试(内含面试资料|面试题|源码)
Selenium: Element wait
说说js中使用for in遍历数组存在的bug
小心你的字典和样板代码
pytorch、tensorflow对比学习—张量
【MySQL必知必会】 表的优化 | 充分利用系统资源
I met a shell script
Robot_Framework: Assertion
4D line-by-line analysis and implementation of Transformer, and German translation into English (3)
混合型界面:对话式UI的未来








![[MySQL] 多表查询](/img/f0/c158750a5a84155ee82729daba2bb3.png)
