Question

In JavaScript, I can declare a string in the following ways;

var a = "Hello World";
var b = new String("Hello World");

but a is not an instance of String...

console.log(a instanceof String); //false;
console.log(b instanceof String); //true;

So how do you find the type or "instanceof" a string literal?

Can JavaScript be forced to create a new String() for every string literal?

Était-ce utile?

La solution

use typeof "foo" === "string" instead of instanceof.

Autres conseils

Use typeof instead and just compare the resulting string. See docs for details.

There is no need to write new String() to create a new string. When we write var x = 'test'; statement, it create the x as a string from a primitive data type. We can't attach the custom properties to this x as we do with object literal. ie. x.custom = 'abc'; x.custom will give undefined value. Thus as per our need we need to create the object. new String() will create an object with typeof() Object and not string. We can add custom properties to this object.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top