1.操作符
(1)typeof操作符
- 格式:type=typeof variable
- 能判断类型有:number、string、boolean、symbol、undefined、function、bigint(ECMAScript 2020 新增);
- object、array、null 的类型都返回 object
- 返回值为字符串。一共8种(number、string、boolean、undefined、symbol、bigint、function、object)
//判断时也应该加上引号,表示字符串 typeof f === 'function' typeof NaN === 'number'
typeof NaN返回number!!!
(2)instanceof操作符:用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
格式:result=variable instanceof constructor
返回值:true false
function Father() { } let f = new Father(); function Son(){ } Son.prototype = new Father(); let s = new Son(); let d = new Number(12) console.log(f instanceof Father);// true console.log(s instanceof Father);// true console.log(d instanceof Number); //true console.log(12 instanceof Number); //false,不能判断不是用new创建的基本数据类型
2. 方法
(1)constructor.name
function Foo() { } var f1 =new Foo(); console.log(f1.constructor);//ƒ Foo() { [native code] } console.log(f1.constructor.name);//Foo var d = new Number(1) console.log(d.constructor.name) // Number var date = new Date(); console.log(date.constructor.name)// Date var arr = [1, 'abc']; console.log(arr.constructor.name) // Array var reg = /i+/gi; console.log(reg.constructor.name) // RegExp
(2)Object.prototype.toString() 为 Object 对象的实例方法,默认情况下(即不重写该方法),toString()返回 “[object type]”,其中type是对象的类型。
Object.prototype.toString.call(arr) === '[object Array]';//true
[object Object] [object Number] [object Undefined] [object Null] [object String] [object BigInt]
返回的是类型,所以都是大写首字母!!
- 可以区分 null 、 string 、boolean 、 number 、 undefined 、 array 、 function 、 object 、 date 、 math 数据类型。
- 缺点:不能细分为谁谁的实例
3.笔记
要注意 ‘hello’ 和 new String(‘hello’) 的区别,前者是字符串字面值,属于原始类型,而后者是对象。用 typeof 运算符返回的值也是完全不一样的:
typeof 'hello'; // 'string' typeof new String('hello'); // 'object'
String 表示构造函数,’string’ 表示变量的数据类型为字符串。
如果问类型是否为String,则应该判断是否为通过new String得到的,是属于引用类型,用xxx instanceof String即可判断。
如果问类型是否为string,那就是在问该变量是否为一个基本类型的字符串,用typeof xxx === ‘string’来判断
var str1=new String('str1'); var str2='str2'; console.log(typeof str1);//object console.log(typeof str2);//string console.log(str1 instanceof String);//true console.log(str2 instanceof String);//false //如果想要判断字面量形式的string和new出的string均为string,可以添加如下方法: String.prototype.isString=function(str){ return ((str instanceof String) || (typeof str).toLowerCase() == 'string'); }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/199895.html原文链接:https://javaforall.net
