Javascript 当变量达到循环的JS数时返回变量
这个函数有什么错误?我想在bk值达到10后返回它,但结果未定义Javascript 当变量达到循环的JS数时返回变量,javascript,loops,for-loop,Javascript,Loops,For Loop,这个函数有什么错误?我想在bk值达到10后返回它,但结果未定义 <!DOCTYPE html> <html> <head> <script type='text/javascript'> window.onload=function(){ var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var x =
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
x++;
if(x <= 490) {
setTimeout(animate, 33);
}
}
animate();
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
</body>
</html>
window.onload=function(){
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var x=0;
变量y=50;
var宽度=10;
var高度=10;
函数animate(){
clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(x,y,宽度,高度);
x++;
如果(x,因为你的循环永远不会达到10。因为你指定了条件
bk<10
将条件更改为bk您可以将return语句移到循环外,因为bk
的最后一个值是10
。在循环内使用此值进行检查永远不会true
函数domylop(){
对于(var bk=0;bk<10;bk++){
console.log('insode loop',bk);
}
返回bk;//10
}
console.log(domylop());
.as控制台包装{最大高度:100%!重要;顶部:0;}
您有bk<10
作为条件。一旦bk
达到10,条件将失败,迭代将停止,因此不会返回。return
不是一个函数……return bk;
更清楚……顺便问一句,循环直到一个值并检查(类型)有什么意义循环中的最后一个值。您可以将return语句移动到循环之后,而不是在循环中检查n次。