我在写过JavaScript
时遇到了问题。该脚本用于提示用户输入重量,从0到126,然后弹出一个警告框,说明它们所处的重量。
weight class from to
-------------------------------
Fly 0 112
SuperFly 112 115
Bantam 115 118
SuperBantam 118 122
Feather 122 126
<script type="text/javascript">
var weight = parseInt(prompt("What is your weight?"));
if (weight > 126) {
alert('Please enter a weight lighter than 126');
}
document.writeln('<br/>');
var wArray = String ([fly,superfly,bantam,superbantam,feather]);
function recruit() {
if (0 < weight < 112){
document.writeln('You are in' + wArray[0] +'class!');
}
if (112 < weight < 115){
document.writeln('You are in' + wArray[1] +'class!');
}
if (115 < weight < 118){
document.writeln('You are in' + wArray[2] +'class!');
}
if (118 < weight < 122){
document.writeln('You are in' + wArray[3] +'class!');
}
if (122 < weight 126){
document.writeln('Your weight class is' + wArray[4]);
}
</script>
答案 0 :(得分:3)
更改此
var wArray = String ([fly,superfly,bantam,superbantam,feather]);
到这个
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
JavaScript中的所有数组都是动态类型的。没有办法创建一个字符串数组;你只需创建一个数组并用字符串填充它。
此外,
if (115 < weight < 118)
无效。你想要
if (weight > 115 && weight < 118)
答案 1 :(得分:1)
以下是重写代码的第一步:
var weight = prompt("What is your weight?") * 1;
if (weight>126){
alert('Please enter a weight lighter than 126');
}else if (weight > 122){
alert('You are in' + wArray[4] +'class!');
}else if (weight > 118){
alert('You are in' + wArray[3] +'class!');
}else if (weight > 115){
alert('You are in' + wArray[2] +'class!');
}else if (weight > 112){
alert('You are in' + wArray[1] +'class!');
}else{
alert('You are in' + wArray[0] +'class!');
}
现在,看看并考虑如何编写for
循环,并创建一个将限制与名称配对的数据结构。然后你可以循环遍历你的数组,直到你找到正确的条目。
提示:这个怎么样
var classes = [
{ min:123, max:126, name:'fly' },
{ min:119, max:122, name:'superfly' },
// etc.
];