How to “instanceof” a primitive string (string literal) in JavaScript [duplicate]

给你一囗甜甜゛ 提交于 2019-12-05 08:33:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!