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 操作符
返回值 :返回布尔值 truefalse

需要注意的是instanceof 适用于引用数据类型,如对象、数组、函数等。对于基本数据类型(如NumberStringBoolean等),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]"

小结

  • 基本数据类型 :使用typeofObject.prototype.toString.call()来区分。
  • 引用数据类型 :使用instanceofObject.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 属性修改的影响。
相关推荐
JD技术委员会21 分钟前
Rust 语法噪音这么多,是否适合复杂项目?
开发语言·人工智能·rust
Hello.Reader25 分钟前
Rust 中的 `Drop` 特性:自动化资源清理的魔法
开发语言·rust·自动化
Vitalia28 分钟前
从零开始学 Rust:基本概念——变量、数据类型、函数、控制流
开发语言·后端·rust
whisperrr.1 小时前
【JavaWeb12】数据交换与异步请求:JSON与Ajax的绝妙搭配是否塑造了Web的交互革命?
前端·ajax·json
小禾苗_1 小时前
C++ ——继承
开发语言·c++
李长渊哦1 小时前
Java 虚拟机(JVM)方法区详解
java·开发语言·jvm
进击ing小白1 小时前
Qt程序退出相关资源释放问题
开发语言·qt
烂蜻蜓2 小时前
前端已死?什么是前端
开发语言·前端·javascript·vue.js·uni-app
老猿讲编程2 小时前
安全C语言编码规范概述
c语言·开发语言·安全
Rowrey3 小时前
react+typescript,初始化与项目配置
javascript·react.js·typescript