js中如何对数据类型进行区分判断?有几种方法?

1.typeof

返回值 :返回值包括 "undefined", "boolean", "number", "string", "bigint", "symbol", "object" 和 "function"。

需要注意的就是typeof无法区分引用数据类型(对象和数组 ),且对 null的判断为object

javascript 复制代码
typeof 42; // "number"
typeof "Hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof Symbol("id"); // "symbol"
typeof function() {}; // "function"
typeof NaN; // "number"
typeof null; // "object" (这是 JavaScript 的一个历史遗留问题)
typeof {}; // "object"
typeof []; // "object"

2.instanceof 操作符 :
返回值 :返回布尔值 true 或 false

需要注意的是instanceof 适用于引用数据类型,如对象、数组、函数等。对于基本数据类型(如Number、String、Boolean等),instanceof 并不能正确区分。

javascript 复制代码
let arr = [];
arr instanceof Array; // true
let obj = {};
obj instanceof Object; // true
function Person(name) {
    this.name = name;
}
let person = new Person("John");
person instanceof Person; // true

// 对于基本数据类型,instanceof 的行为不如预期:
let num = 42;
console.log(num instanceof Number); // false
let str = "Hello";
console.log(str instanceof String); // false
let bool = true;
console.log(bool instanceof Boolean); // false

3.Object.prototype.toString.call() 方法:

用法 :使用 Object.prototype.toString.call() 方法可以获取对象的内部属性 [[Class]] 的值,从而准确判断其类型。
返回值 :返回一个以 [object 开头、] 结尾的字符串。

javascript 复制代码
Object.prototype.toString.call(42); // "[object Number]"
Object.prototype.toString.call("Hello"); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(function() {}); // "[object Function]"
Object.prototype.toString.call(Symbol("id")); // "[object Symbol]"

小结

  • 基本数据类型 :使用typeof或Object.prototype.toString.call()来区分。
  • 引用数据类型 :使用instanceof和Object.prototype.toString.call()来区分。

小补充:

constructor

javascript 复制代码
(2).constructor === Number// true
([]).constructor === Array // true
隐患:
constructor代表的是构造函数指向的类型,可以被修改的js
function Fn(){}
Fn.prototype = new Array();
var f = new Fn();
// 在这种情况下,f的constructor属性不再指向Fn,而是指向 Array,因为 Fn.prototype 被设置为一个 Array 实例
// 在使用 JavaScript 中的原型继承时,要特别注意 constructor 属性可能带来的不准确性,并在必要时手动重置它以确保类型检测的可靠性。对于类型检测,Object.prototype.toString.call() 方法更为可靠,因为它不受 constructor 属性修改的影响。
相关推荐
半杯咖啡半行码3 分钟前
C++ 编程与 STL 模板:从泛型编程到内存安全详解
开发语言·c++
小兔子9 分钟前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
caoerzhong15 分钟前
JeeWMS 开源 WMS 部署避坑指南:Java 仓库管理系统的环境基线、四类根因与可复现交付
java·开发语言·开源
IT_陈寒15 分钟前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
时间的拾荒人17 分钟前
Qt 界面优化:绘图详解 —— 从基础图形到图片处理
开发语言·qt·面试
MayZork35 分钟前
Qt 文件操作:QSaveFile 与 QTemporaryFile(含 QTemporaryDir)实战
开发语言·qt
北冥you鱼1 小时前
Go 语言空接口(interface{})使用场景与最佳实践
开发语言·windows·golang
xh didida1 小时前
Linux -- 基础IO
linux·服务器·开发语言·c++
个 人 练 习 生1 小时前
C++ string 类模拟实现:从底层理解字符串(上)
开发语言·c++·经验分享·学习·程序人生
guslegend1 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化