我製作了一個有17個球的程序,然後用戶鍵入他想要查看的球的數量。之後,該程序應該在該特定號碼的屏幕上生成隨機數字球。例如。如果用戶說他想看到5個球,他只能輸入5和5個球或者顯示不同的數字。但問題是,輸出不正確,我得到一個錯誤「無法讀取未定義的屬性'ID'」。這裏是我的代碼。我會在代碼中提到我發生錯誤的確切位置。錯誤前無法讀取undefined的屬性
<html>
<head>
</head>
<script type="text/javascript">
window.onload=draw;
function draw(){
var canvas= document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var id;
var x;
var y;
var r;
var i;
var balls=[{"id":1,"x":85,"y":90,"r":40},{"id":2,"x":180,"y":90,"r":40},{"id":3,"x":270,"y":90,"r":40},{"id":4,"x":360,"y":90,"r":40},{"id":5,"x":450,"y":90,"r":40},{"id":6,"x":535,"y":90,"r":40},{"id":7,"x":623,"y":90,"r":40},{"id":8,"x":710,"y":90,"r":40},{"id":9,"x":85,"y":190,"r":40},{"id":10,"x":180,"y":190,"r":40},{"id":11,"x":270,"y":190,"r":40},{"id":12,"x":360,"y":190,"r":40},{"id":13,"x":450,"y":190,"r":40},{"id":14,"x":535,"y":190,"r":40},{"id":15,"x":623,"y":190,"r":40},{"id":16,"x":710,"y":190,"r":40},{"id":17,"x":450,"y":190,"r":40},{"id":18,"x":535,"y":190,"r":40},{"id":19,"x":623,"y":190,"r":40},{"id":20,"x":710,"y":190,"r":40}];
var texts=[];
for(i=0;i<balls.length;i++){
texts[i]=i;
}
var choose;
choose=parseFloat(prompt("enter the number of balls u want to see"));
for (var i=1; i<=choose; i++) {
var x=Math.floor((Math.random() * choose) + 1);
for (var k=1; k<=balls.length; k++) {
var b=balls[k];
if(b.id==x){ /*here is the issue*/
ctx.fillStyle="#800000";
ctx.strokeStyle="#000000";
ctx.beginPath();
ctx.arc(b.x,b.y,b.r,0, 2 * Math.PI);
ctx.stroke();
ctx.fill();
ctx.fillStyle = 'black';
ctx.fillText(b.id, b.x, b.y);
}
}
}
}
</script>
<body>
<canvas id="canvas" width="800" height="800" style="border: 2px solid #000000"></canvas>
</body>
</html>
在0處開始for循環,並且只在'k
Kaiido
現在是得到結果謝謝,但所需的圈數沒有出現:/例如,如果我寫6我得到4或5,當我輸入3我得到2或東西。我如何解決這個問題? –
這是因爲你對第一個循環做了同樣的錯誤:'for(i = 0; i
Kaiido