if ... else语句和数组

if ... else语句和数组

问题描述:

我试图使用if ... else语句并通过数组元素的值将值分配给变量stateCode。有些东西可能无法正常工作。 下面的代码:if ... else语句和数组

<!DOCTYPE html> 
<html> 
<head> 
    <title>if...else</title> 
<script type="text/javascript"> 

function choices() { 
    var stateCode = document.getElementById("x").value; 
    var taxes = new Array(10; 7.5; 3.2); 
    if ("x" === "OR") { 
    document.writeln(taxes[0]); 
    } else if ("x" === "CA") { 
    document.writeln(taxes[1]); 
    } else if ("x" === "MO") { 
    document.writeln(taxes[2]); 
    } 

} 
</script> 
</head> 
<body> 
<p> 
    <select id="x" onchange="choices(this.value);"> 
    <option value = "">---Reset---</option> 
    <option value = "MO">MO</option> 
    <option value = "OR">OR</option> 
    <option value = "CA">CA</option> 
    </select> 

</p>  
</body> 
</html> 
+5

我怀疑字符串' “X”'会永远等于字符串'“或”“。 .. – deceze 2012-04-24 02:21:49

+1

也许你打算写'if(stateCode ===“OR”)'&c。 – 2012-04-24 02:23:12

+2

';'也是'new Array(10; 7.5; 3.2)'中的语法错误。这些应该是逗号,并且确实应该使用数组文字符号:'[10,7.5,3.2]'。 – 2012-04-24 02:24:16

if ("x" === "OR") { 
    document.writeln(taxes[0]); 
    } else if ("x" === "CA") { 
    document.writeln(taxes[1]); 
    } else if ("x" === "MO") { 

更换"x"stateCode,然后再试一次

,并取代var taxes = new Array(10; 7.5; 3.2);

var taxes = new Array(10, 7.5, 3.2); 

它应该工作,它为我工作。

这个怎么样则:本替换你的整个功能:

function choices() { 
    var stateCode = document.getElementById("x"); 
    var taxes = new Array(10, 7.5, 3.2); 
    if (stateCode.value != "") { 
     document.getElementById("taxes").innerHTML = taxes[stateCode.selectedIndex - 1]; 
    } 
} 

,并添加<div id="taxes"></div>某个页面上的。

+1

用'new Array(10,7.5,3)替换'new Array(10; 7.5; 3.2);'2);' – Robin 2012-04-24 02:25:55

+0

@Robin'[10,7.5,3.2]'更好。它更简洁,'新的Array()'的参数充其量是令人困惑的。 – 2012-04-24 02:27:49

+0

我试过了,但还没有工作 – 2012-04-24 02:32:40

嗯,我不确定所有仇恨来自哪里。但是,你有一些问题。

  1. document.writeln从来没有好的JavaScript。它会覆盖文档。意思是你的选择框会消失。
  2. 你必须有一个错字,因为你的字符串比较是愚蠢的。但是,使用===
  3. 内联方法处理程序,onchange="choices(this.value);",并不是最糟糕的事情。但他们应该避免。使用JavaScript,您可以更轻松地处理浏览器之间的不同怪癖。
  4. 现代浏览器将有调试此代码的方法。 Firefox中的Firebug,Internet Explorer中的F12(PC)以及Webkit浏览器中的调试控制台。这些将会告诉你行号,并且让你能够精确地查明问题。
  5. 您目前正在发送内联处理程序中select的值,所以只是使用我的猜测。
  6. new Array语法麻烦。我避开它并使用括号,[10, 3.2, 3]


至于你的问题:

添加HTML

<div id="results"></div> 

...

function choices(stateCode) { 
    var results = document.getElementById("results"); 
    var taxes = [10, 7.5, 3.2]; 

    switch(stateCode) { 
     case "OR": 
      results.innerHTML = taxes[0]; 
      break; 
     case "CA": 
      results.innerHTML = taxes[1]; 
      break; 
     case "MO": 
      results.innerHTML = taxes[2]; 
      break; 
     default: 
      results.innerHTML = "No tax records for entry: " + stateCode; 
      break; 
    } 
} 

Example