比较数字时如何解决问题?

时间:2018-08-31 01:53:11

标签: javascript html css

提示用户输入他们选择的三个数字。输入9位数字并将其与较小的数字进行比较时,表示较小的数字较大。

function myFunction(){
  var num1 = prompt("Enter your first number");
  var num2 = prompt("Enter your second number");
  var num3 = prompt("Enter your third number");

  if (num1 > num2 && num1 > num3){
 document.getElementById("result").innerHTML = "The biggest number was " +num1+ "!!";
  } else if (num2 > num1 && num2 > num3){
 document.getElementById("result").innerHTML = "The biggest number was " +num2+ "!!";
  } else if (num3 > num2 && num3 > num1){
 document.getElementById("result").innerHTML = "The biggest number was "+num3+ "!!";
  }

}

我的JavaScript代码缺少什么,无论数量有多大,该代码都会返回正确的响应?

1 个答案:

答案 0 :(得分:2)

prompt()返回一个字符串,而不是数字。同样,所有HTML表单字段也都返回字符串。因此,如果您尝试比较从它们返回的字符串,它们将进行字符串比较。通过字符串比较,9大于800000。

console.log("9" > "800000");

您需要将字符串转换为数字。

var num1 = prompt("Enter number 1:");
var num2 = prompt("Enter number 2:");
var num3 = prompt("Enter number 3:");
console.log(typeof num1, typeof num2, typeof num3); // Promtps return strings!

// Convert the strings to numbers by prepending a + to it
num1 = +num1;
num2 = +num2;
num3 = +num3;

console.log(typeof num1, typeof num2, typeof num3); // Now, they are numbers

// Put numbers into an array
var nums = [num1, num2, num3];

// Sort the array (ascending) and report on the highest number
// which will now be last item in the array.
console.log("Highest number is:", nums.sort()[nums.length-1]);