Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当变量达到循环的JS数时返回变量_Javascript_Loops_For Loop - Fatal编程技术网

Javascript 当变量达到循环的JS数时返回变量

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 =

这个函数有什么错误?我想在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 = 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次。