var a = "hello"
a instanceof String ===> false
var a = new String("hello")
a instanceof String ====> true
var b = [1,2]
b instanceof Array ===> true
var b = new Array(1,2)
b instanceof Array ===> true
为什么String 的两次结果是不一样的,而Array是一样的
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
typeof操作符可以判断出number、boolean、string、function和undefined;( typeof 是一个操作符,主要的目的是检测一个变量是不是基本数据类型的变量,同时也可以说是确定一个变量是字符串,数值,布尔值,还是undefined的最佳工具。但 typeof null == 'object')
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。(基本类型不在链上,所以不适合检测基本类型(都是false))
其实typeof和instanceof的目的都是检测变量的类型,两个的区别在于typeof一般是检测的是基本数据类型,instanceof主要检测的是引用类型!
instanceof String
第一种没有原型链,undefined,所以是false。通过 new String()创造的是一个对象。
instanceof Array
两个都是数组对象。
关于基本数据类型的属性读取
在《JavaScript高级程序设计》中基本包装类型部分有详细的介绍,并且也对下面这两种不同方式有介绍。
针对在评论中的内容,摘录此部分:
instanceof
这个链接里例子部分有string的例子。
string创建
这个链接里有别人回答的字符串创建的方式。