简体   繁体   中英

Why doesn't this work in JavaScript if the value is a string?

All indicators is that this code should work. It does not. Check it out:

aString = "Why doesn't this work?";

if ( typeof aString == String) {
alert("I am a string!!!");
}

Only if I add quotations and make string minuscule, does it work.

aString = "This does work, but why?";

if ( typeof aString == 'string') {
alert("I am a string!!!");
}
var a = 'str';
console.log(typeof a);

Here typeof a returns 'string' not String . String is a constructor function. That's why in first case it does not work.

That is because typeof actually returns a string stating the type.

So you have to compare it to a string as well, such as "string" .

Be careful of the following

 var myString = new String('Hallo what's up');

 console.log(typeof myString); // Object

Run below two codes in browser console and you will know the difference.

  var abc = 'New string'
  console.log(abc)

  var def = new String('Another string')
  console.log(def);

You are comparing a string with its constructor function .

Read about primitive string value and String object.

 aString = "Why doesn't this work?"; if ( typeof aString === String) { console.log("I am a string, but typeof returns a string and not String constructor!!!"); } aString = "Why does this work?"; if ( typeof aString === 'string') { console.log("aString is a string and typeof aString returns 'string'!!!"); } console.log("A string is not equal to its constructor->",'string' !== String); console.log("Any strings constructor is equal to String constructor->",'string'.constructor === String); console.log("This is not useful in typeof as all results are strings even if it is number or boolean ->",(typeof 43).constructor === String); console.log("The useful comparison would be ->",typeof 43 === "number");

Table for return values of typeof

typeof "any string" === "string";//true
typeof new String('hey') === "object";//true
Object.prototype.toString.call(new String('hey')) === "[object String]";//true
typeof (new String('hey')).valueOf() === "string";//true

Only the second version of your code is correct because typeof is intended to return the type of an object as a string representation. When you use typeof on a String you receive 'string'.

You can read the details in the ECMAScript® 2016 Language Specification .

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