Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何";instanceof";JavaScript中的基本字符串(字符串文字)_Javascript_String_Instanceof_String Literals - Fatal编程技术网

如何";instanceof";JavaScript中的基本字符串(字符串文字)

如何";instanceof";JavaScript中的基本字符串(字符串文字),javascript,string,instanceof,string-literals,Javascript,String,Instanceof,String Literals,在JavaScript中,我可以通过以下方式声明字符串: var a = "Hello World"; var b = new String("Hello World"); 但a不是字符串的实例 console.log(a instanceof String); //false; console.log(b instanceof String); //true; 那么如何找到字符串文本的类型或“实例” 是否可以强制JavaScript为每个字符串文本创建一个新字符串()?使用typeof,只

在JavaScript中,我可以通过以下方式声明字符串:

var a = "Hello World";
var b = new String("Hello World");
但a不是字符串的实例

console.log(a instanceof String); //false;
console.log(b instanceof String); //true;
那么如何找到字符串文本的类型或“
实例”


是否可以强制JavaScript为每个字符串文本创建一个
新字符串()

使用
typeof
,只需比较结果字符串即可。有关详细信息,请参见。

使用
类型的“foo”==“string”
而不是
实例。无需编写
新字符串()
来创建新字符串。当我们写
varx='test'时
语句,它将
x
作为原始数据类型的字符串创建。我们不能像对待object literal那样将自定义属性附加到此
x
。例如,
x.custom='abc'
x。自定义
将给出未定义的值。因此,根据我们的需要,我们需要创建对象
newstring()
将使用
typeof()对象而不是字符串创建对象。我们可以向该对象添加自定义属性。

谢谢您的文档链接;但同样重要的是:“instanceof操作符测试对象的原型链中是否存在constructor.prototype。”对不起,你能解释一下原因吗?@NinjaCoding基本上你可以检查问题开头提供的链接。你会找到更详细的解释。但是本质上,
String
对象不是原语,这就是问题所在。欢迎使用js=)如果它实际上是一个
字符串
(function(){return typeof this;})。调用('foo')
对象
),回答实际问题,以防你真的喜欢使用
实例
(像我一样,讨厌
typeof=
垃圾)您可以在检查对象时轻松地将其强制为对象。在代码
Object.defineProperty(Object.prototype,'.\u Object',{get:function(){return this;}}})中点击此项和瞧,
'string.\u string的对象实例
返回
true
!如果需要,您可以避免使用原型并生成函数,但这会生成最优雅的if语句