JavaScript类型

时间:2016-11-16 11:50:50

标签: javascript typeof

我有一个关于codeschool.com函数练习的问题,结论是......

function countE() {
  var phrase = prompt("Which phrase would you like to examine?");

  if (typeof(phrase) != "string") {
    alert("This is not a valid entry!");
    return false;
  } else {
    var eCount = 0;

    for (var i = 0; i < phrase.length; i++) {
      if (phrase.charAt(i) === 'e' || phrase.charAt(i) === 'E') {
        eCount++;
      }
    }
    alert(eCount);
    return true;
  }
}
countE()

所以..我想测试什么不是字符串,我想得到警告&#34;这不是一个有效的条目!&#34;。

但是,如果提示只返回一个字符串,那么为什么呢 &LT;&LT; if(typeof(phrase)!=&#34; string&#34;)&gt;&gt;包含在函数中?

很抱歉在这里提出这个基本问题,codechool讨论页面没有给我答案,我很想知道。

谢谢。 Ĵ

1 个答案:

答案 0 :(得分:0)

Cancel Esc 将返回null。这是您应该感兴趣的支票。

cancel

preview

参考:MDN prompt

注意:您不需要将()typeof一起使用。所以改成它:

if (typeof phrase != "string") {

其他方案

当您期望一个数字,如年龄或某事时,您可以使用:

if (isNaN(phrase)) {

上述内容可能会帮助您确定它是否为数字。