JS typeof 与 instanceof

JS中经常使用来断定变量类型的两个函数为 typeof 和 instanceofphp

typeof 的结果有 

undefined, number, boolean, string, function, 
object[
null, 
Array,
String,
Date.....]

要注意的地方是 typeof null的结果为object, null在js中是一种特殊的对象,而非等同于 undefinedsql

null 和 undefined 并非等价的函数

var tmp = null; // 虽然tmp是null,但我也定义了
var undef; //声明但没定义
alert(typeof tmp); // object
alert(typeof undef); // undefined

因此判断一个值是否是null的时候直接用 tmp == null便可,切勿使用typeof,null是一种特殊的对象spa

// 标量 //
typeof 123; // number
typeof 'string'; // string
typeof true; // boolean
// 函数 //
typeof function(){}; //function
// 对象 //
typeof new String('string'); // object
typeof null; //objecttype

而判断一个变量是否被定义则可code

var temp;
typeof temp === "undefined"; //true 类型名
temp == undefined; //true 全部未定义的变量其实都是undefined

instanceof 能够判断非标量的类型

1 instanceof Number; //false
new Number(1) instanceof Number; //true
'string' instanceof String; // false
new String('string') instanceof String; // true
true instanceof Boolean; //false
new Boolean(true) instanceof Boolean; //true

注意 js 中分为引用类型和对象实例,new 一个引用类型构造函数可返回此类型的一个实例,类型能够本身建立,也能够使用咱们平时经常使用的 Object Array Date 等,同事要注意标量并非但能够转换为某类型的实例对象

相关文章
相关标签/搜索