首页 > 解决方案 > 为什么即使输入正确的数字后我仍然会得到“假”?

问题描述

你能找出这里有什么问题吗?为什么即使输入正确的数字后我仍然会得到“假”?这是我的代码..

var rand = Math.floor(Math.random() * 10);
var guess = window.prompt('guess the number!');
if (rand === guess)
  console.log('correct');
else
  console.log('false');
console.log(`correct number is : ${rand}`);

标签: javascript

解决方案


这是因为您使用了严格的相等运算符===,它也考虑了数据类型。该rand值是一个数字,但该guess值是一个字符串。因此,即使表示的值相同,两者也永远不会相等。

var rand = Math.floor(Math.random() * 10);
var guess = window.prompt('guess the number!');

console.log(typeof rand);
console.log(typeof guess);

你可以通过使用相等运算符来解决这个问题..

var rand = Math.floor(Math.random() * 10);
var guess = window.prompt('guess the number!');

if (rand == guess)
  console.log('correct');
else
  console.log('false');
console.log(`correct number is : ${rand}`);

..将rand数字更改为字符串..

var rand = Math.floor(Math.random() * 10);
var guess = window.prompt('guess the number!');

if (rand.toString() === guess)
  console.log('correct');
else
  console.log('false');
console.log(`correct number is : ${rand}`);

..或通过将guess字符串更改为数字

var rand = Math.floor(Math.random() * 10);
var guess = window.prompt('guess the number!');

if (rand === parseInt(guess, 10))
  console.log('correct');
else
  console.log('false');
console.log(`correct number is : ${rand}`);


推荐阅读