为什么导致以下javascript代码返回值“20”insetad为“10”? [英] Why does result in the following javascript code return a value of “20” insetad of “10”?
本文介绍了为什么导致以下javascript代码返回值“20”insetad为“10”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< html >
< head >
< script src = http ://code.jquery.com/jquery-1.10.1.min.js > < ; / script >
< script >
function incrementby(start,numberofiterations){
var s = start
var n = numberofiterations;
返回函数(){
for(var i = s; i < n; i ++)
result ++;
alert('variable 结果 等于 ' + result);
}
} < span class =code-attribute>
var incrementtest = incrementby(0, 10);
< / script >
< / head < span class =code-keyword>>
< body >
< div <温泉n class =code-keyword>> 为什么上面的incrementby()中的警报表示变量result等于20而不是10?< / div >
< div > < 按钮 id = 运行 > 运行< / button > < / div >
< 脚本 >
$(function(){
$(#run)。click(incrementtest) ;
});
结果= 10;
< / script >
< / body >
< / html >
解决方案
(function(){
(#run ).click(incrementtest);
});
结果= 10;
< / script >
< / body >
< / html >
加载页面时
结果
初始化为10
。之后,当您单击运行按钮时,您调用incrementtest
,并使用额外的10
递增它。 / p>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function incrementby(start, numberofiterations) {
var s = start
var n = numberofiterations;
return function(){
for (var i = s; i < n; i++)
result++;
alert('variable "result" equals ' + result);
}
}
var incrementtest = incrementby(0, 10);
</script>
</head>
<body>
<div>Why does the alert in incrementby() above say that variable "result" equals 20 instead of 10?</div>
<div><button id="run" >Run</button></div>
<script>
$(function(){
$("#run").click(incrementtest);
});
result = 10;
</script>
</body>
</html>
解决方案
(function(){
("#run").click(incrementtest); }); result = 10; </script> </body> </html>
When the page is loaded
result
is initialized with10
. After that, when the you click the "run" button you callincrementtest
and, increment it with additional10
.
这篇关于为什么导致以下javascript代码返回值“20”insetad为“10”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文