免责声明:我是个白痴。
这非常简单。我必须做一些非常基本的错误,但我花了很多时间试图弄清楚,我很难过。
供参考,整个代码:
<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
那么,我哪里错了?