Object.prototype.toString vs typeof
2016-09-01 10:48
411 查看
var start = new Date(); for(var i = 0; i < 100000000; i++){ Object.prototype.toString.call(1)}; var end = new Date(); console.log(end-start);
执行时间:33526
var start = new Date(); for(var i = 0; i < 100000000; i++){ typeof 1}; var end = new Date(); console.log(end-start);
执行时间:212
由此可见typeof的效率高出很多,这个在jQuery源代码也有所体现:
type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }
只有检测到对象是object或者function的时候,才会去调用Object.prototype.toString,否则直接调用typeof。
----------------------------------------
以下为typeof和Object.prototype.toString的返回值对比:
typeof []; // object typeof {}; // object typeof ''; // string typeof new Date() // object typeof 1; // number typeof function () {}; // function typeof /test/i; // object typeof true; // boolean typeof null; // object typeof undefined; // undefined
Object.prototype.toString.call([]); // [object Array] Object.prototype.toString.call({}); // [object Object] Object.prototype.toString.call(''); // [object String] Object.prototype.toString.call(new Date()); // [object Date] Object.prototype.toString.call(1); // [object Number] Object.prototype.toString.call(function () {}); // [object Function] Object.prototype.toString.call(/test/i); // [object RegExp] Object.prototype.toString.call(true); // [object Boolean] Object.prototype.toString.call(null); // [object Null] Object.prototype.toString.call(); // [object Undefined]
参考链接:
https://toddmotto.com/understanding-javascript-types-and-reliable-type-checking/
相关文章推荐
- js判断对象类型 typeof与Object.prototype.toString.call方法的区别
- jquery判断变量类型typeof和Object.prototype.toString.apply()
- 判断变量的类型(typeof、instanceof、Object.prototype.toString)
- Object.prototype.toString & typeof
- Json解析异常处理方式(JSONException: Value of type java.lang.String cannot be converted to JSONObject)
- Object of type 'String' cannot be converted to type 'Function'
- alue of type java.lang.String cannot be converted to JSONObject
- org.json.JSONException: Value ok of type java.lang.String cannot be converted to JSONObject: [Caugh
- js 原始类型 内置对象 protype instanceof construcor Object.prototype.toString.call()
- Value of type java.lang.String cannot be converted to JSONObject
- 【web前端】typeof和object.toString.call()的区别
- cannot pass non-trivial object of type 'string' to variadic function
- 判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解
- Value of type java.lang.String cannot be converted to JSONObject 异常
- JSONException: Value of type java.lang.String cannot be converted to JSONObject
- 【web前端】typeof和object.toString.call()的区别
- js instanceof、typeof、Object.prototype.toString.call(obj)的用法和区别
- org.json.JSONException: Value ok of type java.lang.String cannot be converted to JSONObject:
- of type java.lang.String cannot be converted to JSONObject: Android
- 判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解