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

标签 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 输入到输入文本字段中时,我得到“false”输出。 但 10 和 50 确实返回 true。简而言之:结果是不可预测的。我认为它可能会作为字符串进行评估,但是当我研究它时,我所能发现的是 Javascript 具有动态数据类型,并且如果变量是数字,则会将变量作为数字进行比较。即:

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

那么,我哪里出错了?

最佳答案

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

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

关于javascript比较运算符无法正确评估用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18857240/

相关文章:

javascript - 在 R Shiny 中显示逗号和条件突出显示 - 不兼容

javascript - Javascript 中是否可以为匿名调用函数提供参数计数?

javascript - 如何禁用 hook.io 中的输出

javascript - 使用 jQuery 处理 HTML 表的列

javascript - Awesomium:包含外部 javascript

javascript - 下拉菜单类似于xenForo?

php - JSON字符编码与utf8的比较

JavaScript/SoundManager2 - 不播放任何东西

php - Javascript 动态变量名

javascript - 如何使用 JavaScript 上传嵌入图像?