简体   繁体   中英

JavaScript typeof

I have a question about a codeschool.com function exercise which concluded as this...

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()

So.. I wanted to test what is not a string, I wanted to get the alert "This is not a valid entry!".

But, if a prompt only returns a string then why is this << if (typeof(phrase) != "string") >> included in the function?

Sorry to ask this basic question here, codeschool discussion page did not give me an answer and I am very curious to know.

Thank you. J

Pressing Cancel or Esc will return null . This is the check you should be interested in.

取消

预习

Reference: MDN prompt .

Note: You don't need to use () with typeof . So change it to:

if (typeof phrase != "string") {

Other Scenarios

When you are expecting a number, like age or something, you can use:

if (isNaN(phrase)) {

The above might help you to decide if it is a number or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM