Javascript while循环使用if / else语句

时间:2017-11-06 23:16:36

标签: javascript

我试图让这个程序显示"输出"当"值"不是3,但它会显示"输出3"如果值为IS 3.但不知何故,这不起作用。请帮忙。



function changeText() {

  var x = 1;
  var value = document.getElementById("userInput").value;
  var output = document.getElementById("output");
  var finalx = " ";

  while (x <= value) {

    if (x = 3) {
      finalx += "Output" + x + " ";

    } else {
      finalx += "Output";

    }
    x++;
  }

  output.innerHTML = finalx;
}
&#13;
<div id="output"> Your Output will be displayed here </div>
<br>
<br>

<input type="text" id="userInput" />
<br>
<br>
<input type="submit" id="box" value="Click me" onclick="changeText();" />
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:5)

if (x = 3) 

实际上,您将3分配给x并始终返回true(非零)。你需要的是

if (x === 3)

你真的不需要这里的循环。只需要检查值

if (value == 3) 

答案 1 :(得分:0)

x=3更改为x===3进行比较