简单的javascript函数无法正常工作。为什么呢?

时间:2018-05-15 22:24:34

标签: javascript nan console.log

出于某种原因,无论我绑定到变量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

3 个答案:

答案 0 :(得分:0)

您必须将参数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);

答案 1 :(得分:0)

在JS中,NaN是一个不同类型的值,对于字符串基本上是NaN,对于int是NaN等,该方法正在做的是检查传递的值是否为Number类型的NaN。

答案 2 :(得分:0)

使用“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”函数将返回变量“x”的类型。