javascript比较运算符未正确评估用户输入

时间:2013-09-17 18:28:31

标签: javascript

免责声明:我是个白痴。

这非常简单。我必须做一些非常基本的错误,但我花了很多时间试图解决这个问题,而且我很难过。

供参考,整个代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Not comparing correctly</title>
</head>
<script>

//This is the main function. It creates a new game and plays it.
function playTheGame() {
    "use strict";
    //create the game object
    var currentGame = new game();
    //play the game
    currentGame.play(document.getElementById("eCurrentStake").value, document.getElementById("eGoalAmount").value);
}

// This is the game object.
function game(){
    //properties
    this.goalAmount = 0;
    this.currentStake = 0;

    //Play method Plays the game and stores the results in properties
    this.play=play;
    function play(currentStake,goalAmount){
        //set the relevant properties to values passed to the object
        this.goalAmount = goalAmount;
        this.currentStake = currentStake;
        alert(this.currentStake+" < "+this.goalAmount+" :"+(this.currentStake < this.goalAmount));
    };
}
</script>

<body>
    Enter Current Stake: <input type="text" id="eCurrentStake"></input><br>
    Enter Goal Amount: <input type="text" id="eGoalAmount"></input><br>

    <button type="button" onclick="playTheGame()">Let's Play!</button>
</body>
</html>

给我带来麻烦的代码部分:

alert(this.currentStake+" < "+this.goalAmount+" :"+(this.currentStake < this.goalAmount));

当我将9和10放入输入文本字段时,我得到一个“假”输出。 但10和50确实返回真实。简而言之:结果是不可预测的。我认为它可能是作为一个字符串进行评估,但是当我研究它时,我所能找到的只是Javascript具有动态数据类型,并且如果它们是数字则将变量作为数字进行比较。即:

http://www.w3schools.com/js/js_datatypes.asp

那么,我哪里错了?

5 个答案:

答案 0 :(得分:2)

可能需要使用parseInt将参数转换为数字:

this.goalAmount = parseInt(goalAmount);
this.currentStake = parseInt(currentStake);

答案 1 :(得分:0)

将您想要与parseInt进行比较的内容换行以将其转换为数字 - 否则它们将被比较为字符串

答案 2 :(得分:0)

您可以使用数字功能: http://www.w3schools.com/jsref/jsref_number.asp

答案 3 :(得分:0)

您怀疑输入值确实是字符串。把它们投射到数字:

this.goalAmount = Number(goalAmount);
this.currentStake = Number(currentStake);

归结为:

"9" < "10" // false
Number("9") < Number("10") // true

答案 4 :(得分:0)

更改此行

currentGame.play(parseInt(document.getElementById("eCurrentStake").value), parseInt(document.getElementById("eGoalAmount").value));