for-in问题总结,具体可以参见代码,列出几种情况。
<!DOCTYPE html>
<html>
<head>
<<meta charset="utf-8">
<title>for in有问题</title>
</head>
<body>
<script type="text/javascript">
document.write("<br/>=========一般用for循环=========<br/>");
var a = []; // Create a new empty array.
a[5] = 5; // Perfectly legal JavaScript that resizes the array.
for (var i = 0; i < a.length; i++) {
// Iterate over numeric indexes from 0 to 5, as everyone expects.
document.write(a[i]+" ");
}
document.write("<br/>=========使用for-in==========<br/>");
var a = [];
a[4] = 4;
a[5] = 5;
for (var x in a) {
// Shows only the explicitly set index of "5", and ignores 0-4
document.write(a[x]+" ");
}
document.write("<br/>=========使用for-in有问题的情况===========<br/>");
// Somewhere deep in your JavaScript library...
Array.prototype.foo = 1;
// Now you have no idea what the below code will do.
var a1 = [1, 2, 3, 4, 5];
for (var x in a1) {
// Now foo is a part of EVERY array and
// will show up here as a value of 'x'.
//document.write(x+" ");
document.write("<br/>");
document.write(a1[x]+" ");
}
document.write("<br/>=========二维数组中使用for-in(将上面的注释后运行)=========");
var adj=[];
for (var i = 0; i < 10; i++) {
adj[i]=[];
adj[i].push(i);
}
adj[5].push(2);
adj[5].push(3);
adj[5].push(4);
adj[5].push(9);
for(var w in adj[5]){
document.write(w);
document.write("<br/>");
//document.write(adj[w]);
}
console.log(adj);
document.write("<br/>=========使用for-in遍历对象=========");
for(var x in window){
document.write(x);
document.write("<br/>");
}
</script>
</body>
</html>