【问题标题】:Assigning a boxing weight class分配拳击重量等级
【发布时间】:2011-12-05 22:13:06
【问题描述】:

我在写的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>

【问题讨论】:

  • 请注意,您的函数缺少一个结束 }。适当且一致的缩进(我已应用于您的问题)将帮助您注意到这样的事情。

标签: javascript logic helper


【解决方案1】:

改变这个

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)

【讨论】:

    【解决方案2】:

    这是重写代码的第一步:

    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.
    ];
    

    【讨论】:

    • 你得到了我今天的最后一个 +1,但老实说,我认为 OP 在飞行之前需要学会走路:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多