0

免责声明:我是个白痴。

这非常简单。我必须做一些非常基本的错误,但我花了很多时间试图弄清楚,我很难过。

供参考,整个代码:

<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 确实返回 true。简而言之:结果是不可预测的。我认为它可能正在评估为一个字符串,但是当我研究它时,我只能发现 Javascript 具有动态数据类型,并且如果它们是数字,它们会将变量作为数字进行比较。IE :

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

那么,我哪里错了?

4

5 回答 5

2

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

this.goalAmount = parseInt(goalAmount);
this.currentStake = parseInt(currentStake);
于 2013-09-17T18:33:14.823 回答
0

包装您要比较的东西parseInt以将它们转换为数字 - 否则它们将作为字符串进行比较

于 2013-09-17T18:31:20.270 回答
0

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

于 2013-09-17T18:31:40.427 回答
0

正如您所怀疑的,输入值确实是字符串。将它们转换为数字:

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

归结为:

"9" < "10" // false
Number("9") < Number("10") // true
于 2013-09-17T18:32:16.177 回答
0

更改此行

currentGame.play(parseInt(document.getElementById("eCurrentStake").value), parseInt(document.getElementById("eGoalAmount").value));
于 2013-09-17T18:33:35.560 回答