问题
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?
回答1:
use typeof "foo" === "string"
instead of instanceof.
回答2:
Use typeof
instead and just compare the resulting string. See docs for details.
回答3:
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.
来源:https://stackoverflow.com/questions/16792051/how-to-instanceof-a-primitive-string-string-literal-in-javascript