JS类型判断

11次阅读

共计 2289 个字符,预计需要花费 6 分钟才能阅读完成。

JS 数据类型判断
有的时候需要判断数据类型,应对各种复杂的逻辑判断,先来个咱们最常用的。
1.typeof
typeof 操作符返回一个字符串,并表示该变量的类型。
typeof oper / typeof (operand)
var testString = ‘adus’,
testArray = [],
testBoolean = true,
testNumber = 0,
testObject = {},
testNull = null,
testUndefined = undefined

console.log(typeof testString);//string
console.log(typeof testArray);//object
console.log(typeof testBoolean);//boolean
console.log(typeof testNumber);//number
console.log(typeof testObjec);//object
console.log(typeof testNull);//object
console.log(typeof testUndefined);//undefined

当然不只有上面的这些基础类型,还有下面这些:

Symbol(ECMAScript 6 新增)“symbol”

宿主对象(由 JS 环境提供)Implementation-dependent

函数对象([[Call]] 在 ECMA-262 条款中实现了)“function”

咦?有点不对,为什么数组、null 等都是 object 呢???请往下看
Function 或者 Array 这些类型的实例的时候,其实都是基于 Object 实例进行的一种扩展。只是多了一些特有属性。

在 JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。

由于 null 代表的是 空指针(大多数平台下值为 0x00)。

因此,null 的类型标签也成为了 0,typeof null 就错误的返回了 ”object”。(reference)

2.instanceof
instanceof 运算符用于测试构造函数的 prototype 属性是否出现在对象的原型链中的任何位置, 通俗点说就是一个变量是否某个对象的实例。
object instanceof constructor
object 要检测的对象 / constructor 构造函数
function fnc(){}
var newFnc = new fnc();
console.log(newFnc.__proto__ == fnc.prototype);//true
console.log(newFnc instanceof fnc) //true

/*String 对象和 Date 对象都属于 Object 类型和一些特殊情况 */

var simpleStr = “This is a simple string”;
var myString = new String();
var newStr = new String(“String created with constructor”);
var myDate = new Date();
var myObj = {};
var myNonObj = Object.create(null);

simpleStr instanceof String; // 返回 false, 检查原型链会找到 undefined
myString instanceof String; // 返回 true
newStr instanceof String; // 返回 true
myString instanceof Object; // 返回 true

myObj instanceof Object; // 返回 true, 尽管原型没有定义
({}) instanceof Object; // 返回 true, 同上
myNonObj instanceof Object; // 返回 false, 一种创建对象的方法,这种方法创建的对象不是 Object 的一个实例

myString instanceof Date; // 返回 false

myDate instanceof Date; // 返回 true
myDate instanceof Object; // 返回 true
myDate instanceof String; // 返回 false
3.Object.prototype.toString()
每个对象都有一个 toString() 方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString() 方法被每个 Object 对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 “[object type]”,其中 type 是对象的类型。
Function.prototype.call(thisArg) / Function.prototype.apply(thisArg)
传递要检查的对象作为第一个参数,称为 thisArg。
var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

在合适的场景用恰当的方法,会很省心,也能保证代码的简洁、健壮。

正文完
 0