我是Javascript的初学者,无法获得以下代码。当我点击按钮时,没有任何反应。有人能指出我做错了吗?谢谢!
<html>
<head>
<title>Sarah's Puppy Game</title>
</head>
<body>
<div id="input">
<input id="puppyNumber" size=30>
<button onClick="doLoop()"> Get your puppies </button>
</div>
<script type="text/html">
function doLoop() {
var number = document.getElementById('puppyNumber').value;
var puppy = [];
while (var i = 0; i < parseInt(number); i++) {
puppy = puppy.push('puppy<br>');
}
alert(puppy);
}
</script>
</body>
</html>
答案 0 :(得分:5)
我看到的三个问题。
首先,对text/javascript
<script type='text/javascript'>
其次,在循环中将while
更改为for
。 while
循环用于测试条件,但您已设置计数器。
Thrid,请勿使用puppy
方法指定push()
。 .push()
直接作用于数组。
Here's the corrected version in action.
<!-- type="text/javascript" not "text/html" -->
<script type="text/javascript">
function doLoop() {
var number = document.getElementById('puppyNumber').value;
var puppy = [];
// This is a for loop, rather than a while loop
// Also for good measure, use the second param to parseInt() for a
// decimal radix to avoid getting binary or octal numbers accidentally.
for (var i = 0; i < parseInt(number, 10); i++) {
// Don't assign the result back to puppy
puppy.push('puppy<br>');
}
alert(puppy);
}
</script>
答案 1 :(得分:1)
而不是......
puppy = puppy.push('puppy<br>');
......只是说...
puppy.push('puppy<br>');
push
返回被推送的元素,而不是它被推送到的数组。
您的代码将导致变量puppy
设置为字符串"puppy<br>"
。然后你会尝试"puppy<br>".push("puppy<br>")
,这显然是无效的。