简单的三元运算符不工作

时间:2015-11-13 16:10:04

标签: javascript html html5

我不知道为什么这个简单的三元运算符不起作用。

var numOne = prompt("Enter first number");
var numTwo = prompt("Enter second number");

var outcome = numOne > numTwo ? "First number is bigger" : "Second number is bigger";

document.getElementById("paragraph").innerHTML(outcome); 

3 个答案:

答案 0 :(得分:4)

innerHTML属性,不是方法。

用法应为

document.getElementById("paragraph").innerHTML = outcome;

答案 1 :(得分:4)

您的代码中存在语法错误,innerHTML是您需要为其分配值的属性,而不是函数。您还需要将值转换为整数,否则您的比较将无法在所有情况下都有效。



var numOne = "25"
var numTwo = "111"

var outcome = parseInt(numOne) > parseInt(numTwo) ? "First number is bigger" : "Second number is bigger";
var outcome2 = numOne > numTwo ? "First number is bigger" : "Second number is bigger";

document.getElementById("paragraph").innerHTML="Using integers: " + outcome;
document.getElementById("paragraph2").innerHTML="Using strings: " + outcome2;

<div id="paragraph"></div>
<div id="paragraph2"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:3)

  1. 使用parseInt作为提示,会给你一个字符串。
  2. .innerHTML是属性而非方法(请参阅此link
  3. var numOne = prompt("Enter first number");
    var numTwo = prompt("Enter second number");
    
    var outcome = parseInt(numOne) > parseInt(numTwo) ? "First number is bigger" : "Second number is bigger";
    
    document.getElementById("paragraph").innerHTML = outcome; 
    <div id="paragraph"></div>