为什么我的代码不能正确运行我的IF-ELSE语句?

时间:2016-10-15 14:49:16

标签: javascript if-statement

function checkPIN(pin) {
  if (isNaN(pin)) {
    console.log(pin, ' is not a number');
  } else {
    console.log(pin, ' is a number');
  }  
}

checkPIN(12sf34);

还是很新的,不能为我的生活解决为什么我不能简单地检查是否有某些数字是否有效?

目前我遇到两个错误:

在上面:

  参数列表

之后的

Uncaught SyntaxError:missing)

在类似的代码上,它接受某个东西是一个数字并运行我的控制。但是当它不是一个数字时,它给字母/非数字值一个'未定义'。

我可以在函数中使用isNaN吗? 有什么理由我需要一个额外的括号/括号吗?我不能为我的生活看到一个额外的要求。

4 个答案:

答案 0 :(得分:2)

您在 字符串

周围缺少引号
checkPIN("12sf34");

如果它是一个数字,你就不需要引号,但12sf34显然不是数字

答案 1 :(得分:0)

我会使用typeof来更灵活地测试不同类型的变量。但是给定的不是数字,所以它需要引用。

function checkPIN(pin) {
  if (typeof(pin) != "number") {
    console.log(pin, ' is not a number');
  } else {
    console.log(pin, ' is a number');
  }  
}

checkPIN('12sf34');

答案 2 :(得分:0)

调用checkPIN函数时错过了引号。

这样称呼:

checkPIN('12sf34');

答案 3 :(得分:0)

我认为您的代码有两个不正确的分数

  1. checkPIN(12sf34); //语法错误,需要单引号包装值
  2. checkPIN函数内部的逻辑应使用typeof来检查输入类型
  3. function checkPIN(pin) {
      if (typeof(pin) !== 'number') {
        console.log(`${pin} is not a number`)
      } 
      else {
        console.log(`${pin} is a number`);
      }  
    }
    
    checkPIN('abc1d') // abc1d is not a number
    checkPIN(12345) // 12345 is a number
    checkPIN('12345') // 12345 is not a number
    checkPIN() // undefined is not a number