javascript - 为什么即使输入正确的数字后我仍然会得到“假”?
问题描述
你能找出这里有什么问题吗?为什么即使输入正确的数字后我仍然会得到“假”?这是我的代码..
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
值是一个数字,但该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}`);
推荐阅读
- powershell - foreach 循环中是否存在“如果有”?
- jenkins-pipeline - 使詹金斯并行块更容易被人类理解
- r - 如何用非空数据框中的列填充空数据框?
- android - 将数据传递给 PageKeyedDataSource
- java - 如何有效地索引 n 个线程之间的非平方乘积矩阵?
- python - 规范化嵌套的 JSON 数据
- function - 更改函数中的全局切片
- python - 密码验证器:密码需要包含一个空格字符?
- .net - 我收到此错误:未知错误(0x80005000)
- javascript - Javascript正则表达式引擎:非单词字符的字符串开头的单词边界不匹配