<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <script type="text/javascript"> var arr = [1,2,3]; var out = []; var out2 = []; var as = []; //alert(1=="1");//false //alert(1==="1");//true //alert({}=={});//false //alert({}==={});//false alert([]===""); for(var i = 0; i<arr.length;i++) { var item = arr[i]; as.push(item); out.push(function(){ alert("out:"+item); }); // 并不把for当成一个context,这个时候out添加的function中的item都会是一个值, // 因为item存在于for循环整个作用域,而不是每一次循环 // 更改为如下,可以得到你想要得到的结果 (function(){ out2[i]=function(){ alert("out2:"+arr[i]); }; //out2.push(function(){ alert("out2:"+arr[i]); }); })(); } for(var j=0; j<out.length; j++) { //out[j]();//alert(3);alert(3);alert(3); out2[j]();//alert(1);alert(2);alert(3); //alert(as[j]);//alert(1);alert(2);alert(3); } //out.forEach(function(func){ func(); });// 不支持 //alert(a);//报错,未定义 a = 0; (function foo() { //alert("a1:"+a);//undefined a = 3; //alert("a2:"+a);//3 var a; //alert("a3:"+a);//3 })(); //alert(a);//0 </script> </html>
js容易出错的地方
猜你喜欢
转载自jie66989.iteye.com/blog/1763056
今日推荐
周排行