搜索
写经验 领红包
 > 美食

JavaScipt基础之计算折纸次数训练(js中typeof用法详细介绍)

导语:JavaScript基础之typeof/instanceof

1.typeof操作符返回一个字符串,指示未经计算的操作数的类型。

2.instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

typeof类型及结果

typeof实例

正常

// Numberstypeof 37 === 'number';typeof 3.14 === 'number';typeof Math.LN2 === 'number';typeof Infinity === 'number';typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写typeof Number(1) === 'number'; // 但不要使用这种形式!// Stringstypeof "" === 'string';typeof "bla" === 'string';typeof (typeof 1) === 'string'; // typeof总是返回一个字符串typeof String("abc") === 'string'; // 但不要使用这种形式!// Booleanstypeof true === 'boolean';typeof false === 'boolean';typeof Boolean(true) === 'boolean';// 但不要使用这种形式! // Symbols typeof Symbol() === 'symbol'; typeof Symbol('foo') === 'symbol'; typeof Symbol.iterator === 'symbol'; // Undefined typeof undefined === 'undefined'; typeof declaredButUndefinedVariable === 'undefined'; typeof undeclaredVariable === 'undefined';

// Objectstypeof {a:1} === 'object';// 使用Array.isArray 或者 Object.prototype.toString.call// 区分数组,普通对象typeof [1, 2, 4] === 'object';typeof new Date() === 'object';// 下面的容易令人迷惑,不要使用!typeof new Boolean(true) === 'object';typeof new Number(1) === 'object';typeof new String("abc") === 'object';// 函数typeof function(){} === 'function';typeof class C{} === 'function'typeof Math.sin === 'function';typeof new Function() === 'function';//nulltypeof null === "object";//从一开始js就是这么设计的

2. 使用new操作符会返回一个objectinstanceof实例
// 定义构造函数function C(){} function D(){} var o = new C();o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototypeo instanceof D; // false,因为 D.prototype不在o的原型链上o instanceof Object; // true,因为Object.prototype.isPrototypeOf(o)返回trueC.prototypeinstanceof Object // true,同上C.prototype = {};var o2 = new C();o2 instanceof C; // trueo instanceof C; // false,C.prototype指向了一个空对象,这个空对象不在o的原型链上.D.prototype = new C(); // 继承var o3 = new D();o3 instanceof D; // trueo3 instanceof C; //true

本文内容由小姿整理编辑!