简单 javascript 函数未按预期运行。为什么?
Simple javascript function not working as expected. Why?
出于某种原因,无论我将什么绑定到变量 theNumber,我仍然让控制台输出 numberCheck() 中的第一个 console.log()。我希望这会输出第二个 console.log(),但它拒绝了。我尝试了许多不同的语法更改。可能我就是不明白!Number.isNaN()这个表达式。我认为这意味着如果这个数字是一个数字而不是它的真实数字,但我可能是错的。
记住,我是新来的。我了解术语,因此可以随意使用任何单词进行交流。但是我的 javascript 逻辑很差。
let theNumber = 'god'
function numberCheck(x) {
if (!Number.isNaN(x)) {
console.log('You picked a number')
}
else {
console.log('why won't this log');
}
}
numberCheck(theNumber)
numberCheck(12)
输出:
You picked a number
You picked a number
已修复并按预期工作:
let theNumber = 'god'
function numberCheck(x) {
if (isNaN(x)) {
console.log('You picked a number')
}
else {
console.log('why wont this log');
}
}
numberCheck(theNumber)
numberCheck(12)
输出:
why wont this log
You picked a number
您必须将参数 x
转换为数字
let theNumber = 'god'
function numberCheck(x) {
if (!Number.isNaN(Number(x))) {
console.log('You picked a number');
} else {
console.log('why won\'t this log');
}
}
numberCheck(theNumber);
numberCheck(12);
在 JS 中,NaN 是一个不同类型的值,基本上是字符串为 NaN,整数为 NaN 等,该方法所做的是检查传递的值是否为 Number 类型的 NaN。
使用 "isNaN" 函数有时会很棘手(请参阅文档“https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN”的这一部分)。
由于您似乎只想验证变量是否为数字,因此您可以这样做:
var theNumber = 100;
function numberCheck(x){
if(typeof x === 'number'){
console.log('Nice you picked a number');
}else{
console.log('It is not a number');
}
}
numberCheck(theNumber);
"typeof"函数将return变量的类型"x".
出于某种原因,无论我将什么绑定到变量 theNumber,我仍然让控制台输出 numberCheck() 中的第一个 console.log()。我希望这会输出第二个 console.log(),但它拒绝了。我尝试了许多不同的语法更改。可能我就是不明白!Number.isNaN()这个表达式。我认为这意味着如果这个数字是一个数字而不是它的真实数字,但我可能是错的。
记住,我是新来的。我了解术语,因此可以随意使用任何单词进行交流。但是我的 javascript 逻辑很差。
let theNumber = 'god'
function numberCheck(x) {
if (!Number.isNaN(x)) {
console.log('You picked a number')
}
else {
console.log('why won't this log');
}
}
numberCheck(theNumber)
numberCheck(12)
输出:
You picked a number
You picked a number
已修复并按预期工作:
let theNumber = 'god'
function numberCheck(x) {
if (isNaN(x)) {
console.log('You picked a number')
}
else {
console.log('why wont this log');
}
}
numberCheck(theNumber)
numberCheck(12)
输出:
why wont this log
You picked a number
您必须将参数 x
转换为数字
let theNumber = 'god'
function numberCheck(x) {
if (!Number.isNaN(Number(x))) {
console.log('You picked a number');
} else {
console.log('why won\'t this log');
}
}
numberCheck(theNumber);
numberCheck(12);
在 JS 中,NaN 是一个不同类型的值,基本上是字符串为 NaN,整数为 NaN 等,该方法所做的是检查传递的值是否为 Number 类型的 NaN。
使用 "isNaN" 函数有时会很棘手(请参阅文档“https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN”的这一部分)。 由于您似乎只想验证变量是否为数字,因此您可以这样做:
var theNumber = 100;
function numberCheck(x){
if(typeof x === 'number'){
console.log('Nice you picked a number');
}else{
console.log('It is not a number');
}
}
numberCheck(theNumber);
"typeof"函数将return变量的类型"x".