// 示例代码:JavaScript 中的类型检查
// 1. 使用 typeof 检查基本类型
let str = "Hello, world!";
let num = 42;
let bool = true;
let undef = undefined;
let nul = null;
console.log(typeof str); // 输出: "string"
console.log(typeof num); // 输出: "number"
console.log(typeof bool); // 输出: "boolean"
console.log(typeof undef); // 输出: "undefined"
console.log(typeof nul); // 输出: "object" (这是 JavaScript 的一个历史遗留问题)
// 2. 使用 instanceof 检查对象类型
let arr = [1, 2, 3];
let obj = { key: "value" };
let func = function() {};
console.log(arr instanceof Array); // 输出: true
console.log(obj instanceof Object); // 输出: true
console.log(func instanceof Function); // 输出: true
// 3. 使用 constructor 检查类型
console.log(str.constructor === String); // 输出: true
console.log(num.constructor === Number); // 输出: true
console.log(bool.constructor === Boolean); // 输出: true
console.log(arr.constructor === Array); // 输出: true
console.log(obj.constructor === Object); // 输出: true
console.log(func.constructor === Function); // 输出: true
// 4. 使用 Object.prototype.toString.call 检查类型
console.log(Object.prototype.toString.call(str)); // 输出: "[object String]"
console.log(Object.prototype.toString.call(num)); // 输出: "[object Number]"
console.log(Object.prototype.toString.call(bool)); // 输出: "[object Boolean]"
console.log(Object.prototype.toString.call(undef)); // 输出: "[object Undefined]"
console.log(Object.prototype.toString.call(nul)); // 输出: "[object Null]"
console.log(Object.prototype.toString.call(arr)); // 输出: "[object Array]"
console.log(Object.prototype.toString.call(obj)); // 输出: "[object Object]"
console.log(Object.prototype.toString.call(func)); // 输出: "[object Function]"
typeof
是一种用于检查基本数据类型的运算符,但它对 null
的处理是一个历史遗留问题,会返回 "object"
。instanceof
用于检查对象是否是某个构造函数的实例,适用于自定义对象和内置对象(如数组、函数等)。constructor
属性可以用来检查对象的构造函数,但要注意它可能会被重写。Object.prototype.toString.call()
是一种更可靠的方式,它可以准确地识别所有类型的对象,包括内置类型和自定义类型。上一篇:js typeof用法
下一篇:js assign
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站