string 如何在 JavaScript 中“实例化”一个原始字符串(字符串文字)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16792051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to "instanceof" a primitive string (string literal) in JavaScript
提问by Matthew Layton
In JavaScript, I can declare a string in the following ways;
在 JavaScript 中,我可以通过以下方式声明一个字符串;
var a = "Hello World";
var b = new String("Hello World");
but a is not an instance of String...
但 a 不是 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?
那么如何找到类型或“ instanceof
”字符串文字呢?
Can JavaScript be forced to create a new String()
for every string literal?
可以强制 JavaScriptnew String()
为每个字符串文字创建一个吗?
回答by Artur Udod
use typeof "foo" === "string"
instead of instanceof.
使用typeof "foo" === "string"
代替instanceof.
回答by isaach1000
回答by Vishnudas Tekale
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.
无需写入new String()
即可创建新字符串。当我们编写var x = 'test';
语句时,它x
从原始数据类型创建一个字符串。我们不能x
像处理对象字面量那样将自定义属性附加到它。IE。x.custom = 'abc';
x.custom
将给出未定义的值。因此,根据我们的需要,我们需要创建对象。new String()
将使用typeof()
Object 而不是 string创建一个对象。我们可以向这个对象添加自定义属性。