JavaScript目前有两种数据类型:基本数据类型和引用数据类型。
基本数据类型:Undefined、Null、Boolean、String、Number、Symbol(ES6)
引用数据类型:Object
鉴于ECMAScript是松散类型的,需要有方式检测给定变量的数据类型。下面介绍三种检测数据类型的方法。
1、typeof
typeof是一元运算符,放在起单个操作数的前面,操作数可以是任意类型。
typeof "1"; //"string"typeof 1; //"number"typeof undefined; //"undefined"typeof true; //"boolean"typeof Symbol(); //"symbol"typeof null; //"object"
注:Null类型只有一个值是null。null值是表示一个空对象指针,所以typeof null会返回object。
注:以下三种为判断引用类型数据的方法。
2、instanceof
typeof是检测基本数据类型的得力助手,检测引用类型用途却不大。instanceof通常检测是引用类型。左操作数是待检测其类的对象,右操作数是对象的类。如果左侧的对象是右侧的实例,则返回true,否则返回false。
var d = new Date();// 通过Date()构造函数来创建一个新对象 d instanceof Date; // trued instanceof Object; // true,所有的对象都是Object的实例d instanceof Number; // falsevar a = [1, 2, 3];a instanceof Array; // truea instanceof Object; // true,所有的数组都是对象a instanceof String; // false
想要理解instanceof的工作原理就必须要理解原型链。
以d instanceof Date 为例,JS首先计算Date.prototype,然后在原型链中找 d ,如果找到,那d 是Date的一个实例,表达式返回true。如果Date.prototype不在d 的原型链中的话,那d 不是Date的实例,表达式返回false。
3、constructor属性
构造函数是类的公共标识,所以可以使用construct属性来识别对象是否是某个类的方法。
var s = new String();s.constructor == String; // truevar a = new Array();a.constructor == Array; // true
4、toString()
var a = new Array();Object.prototype.toString(); // "[object Object]"Object.prototype.toString.call(a); // "[object Array]"Object.prototype.toString.call(a).slice(8,-1); // "Array"
原文转载:http://www.shaoqun.com/a/489507.html
卖家网:https://www.ikjzd.com/w/1569
stadium:https://www.ikjzd.com/w/2729
浩方:https://www.ikjzd.com/w/1046
JavaScript目前有两种数据类型:基本数据类型和引用数据类型。基本数据类型:Undefined、Null、Boolean、String、Number、Symbol(ES6)引用数据类型:Object鉴于ECMAScript是松散类型的,需要有方式检测给定变量的数据类型。下面介绍三种检测数据类型的方法。1、typeoftypeof是一元运算符,放在起单个操作数的前面,操作数可以是任意类型。ty
飞书互动:https://www.ikjzd.com/w/1319.html
wario:https://www.ikjzd.com/w/887
湛江六合冰雪世界儿童能去吗?六合冰雪世界多大孩子可以去?:http://tour.shaoqun.com/a/31903.html
去普吉岛旅游需要花费多少钱:http://tour.shaoqun.com/a/64172.html
2020年广州国际灯光节在哪里举行?广州国际灯光节门票多少:http://tour.shaoqun.com/a/72134.html
没有评论:
发表评论