javascript - 关于函数的数值问题?
本文介绍了javascript - 关于函数的数值问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<script type="text/javascript">
var c=[];
for(var i=0;i<8;i++){
c[i]=function abc(){
return console.log(i);
}
}
console.log(c[0]()); //弹出8
for(var j=0;j<8;j++){
function abc(){
console.log(j);
}
abc(); //弹出 0 1 2 3 4 5 6 7
}
</script>
为什么第一个弹出8,而第二个弹出0 1 2 3 4 5 6 7?
解决方案
我们把8改成2,不用for
来解释下。
第一种情况等价于:
var i = 0;
c[0] = function abc() {return console.log(i);};
i ++; // 1
c[1] = function abc() {return console.log(i);};
i ++; // 2
console.log(c[0]()); //即执行console.log(i),明显了i=2
第二种情况等价于:
var j = 0;
function abc() {console.log(j);}
abc(); // 0
j ++; // j = 1
function abc() {console.log(j);}
abc(); // 1
这篇关于javascript - 关于函数的数值问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文