这究竟是不是一个字符串、数字、列表或字典类型?

2026-04-06 11:461阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计191个文字,预计阅读时间需要1分钟。

这究竟是不是一个字符串、数字、列表或字典类型?

plaintext判断对象数据类型的简单方法// 使用 Object.prototype.toString.call() 方法Object.prototype.toString.call(1); // [object Number]Object.prototype.toString.call(null); // [object Null]// typeof 缺点是除 function 外的引用类型都会被识别为 'object'typeof null; // object

这究竟是不是一个字符串、数字、列表或字典类型?

gistfile1.txt

/** * 对象数据类型的判断 */ // Object.prototype.toString() Object.prototype.toString.call(1); // "[object Number]" Object.prototype.toString.call(null); // "[object Null]" // typeof 缺点是除 function 外的引用类型都统一为 "object" typeof null; // "object" typeof {}; // "object" typeof NaN; // "number" 这个也是个坑 // instanceof 可用于区别 null 和 object null instanceof Object; // false // 一个判断数据类型(包括 es6 的 Set 和 Map 对象)的函数 function getType(value) { let type = Object.prototype.toString.call(value).match(/^\[object (.*)\]$/)[1].toLowerCase(); if ( type === 'string' && typeof type === 'object' ) { return 'object'; } // PhantomJS has type "DOMWindow" for null if ( type === null ) { return 'null'; } // PhantomJS has type "DOMWindow" for undefined if ( type === undefined ) { return 'undefined'; } return type; }

本文共计191个文字,预计阅读时间需要1分钟。

这究竟是不是一个字符串、数字、列表或字典类型?

plaintext判断对象数据类型的简单方法// 使用 Object.prototype.toString.call() 方法Object.prototype.toString.call(1); // [object Number]Object.prototype.toString.call(null); // [object Null]// typeof 缺点是除 function 外的引用类型都会被识别为 'object'typeof null; // object

这究竟是不是一个字符串、数字、列表或字典类型?

gistfile1.txt

/** * 对象数据类型的判断 */ // Object.prototype.toString() Object.prototype.toString.call(1); // "[object Number]" Object.prototype.toString.call(null); // "[object Null]" // typeof 缺点是除 function 外的引用类型都统一为 "object" typeof null; // "object" typeof {}; // "object" typeof NaN; // "number" 这个也是个坑 // instanceof 可用于区别 null 和 object null instanceof Object; // false // 一个判断数据类型(包括 es6 的 Set 和 Map 对象)的函数 function getType(value) { let type = Object.prototype.toString.call(value).match(/^\[object (.*)\]$/)[1].toLowerCase(); if ( type === 'string' && typeof type === 'object' ) { return 'object'; } // PhantomJS has type "DOMWindow" for null if ( type === null ) { return 'null'; } // PhantomJS has type "DOMWindow" for undefined if ( type === undefined ) { return 'undefined'; } return type; }