<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>遍历数组</title>
</head>
<body>
<script>
var arr = [1,2,3,[4,[5]]];
Array.prototype.each = function(fn){
try{
this.i || (this.i = 0);
if(this.length > 0 && fn.constructor == Function){
while(this.i < this.length){
var e = this[this.i];
if(e && e.constructor == Array){
e.each(fn);
}else{
// fn.apply(e,[e]);
fn.call(e,e);
}
this.i++;
}
this.i = null;
}
}catch(err){
alert(err)
}
}
arr.each(function(item){
alert(item)
})
</script>
</body>
</html>
javascript原型遍历数组
最新推荐文章于 2022-12-19 15:02:05 发布
本文介绍了一种使用JavaScript自定义方法实现数组遍历的技巧。通过扩展Array.prototype并新增each方法,实现了对数组及其嵌套数组的深度遍历,并通过递归调用确保每个元素都能被访问到。
1064

被折叠的 条评论
为什么被折叠?



