更新时间:2024-03-18 来源:黑马程序员 浏览量:

在前端中,我们可以使用以下方法来判断一个值的类型:
typeof操作符可以用来判断一个值的基本类型,包括"undefined", "boolean", "number", "string", "symbol", "object", "function",但是它并不总是能够准确地区分出对象的具体类型。
typeof 42 // "number"
typeof "hello" // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (typeof null 返回 "object" 是 JavaScript 的历史遗留问题,不是一个准确的类型判断方式)
typeof {} // "object"
typeof [] // "object"
typeof function() {} // "function" instanceof操作符用于检查一个对象是否是另一个对象的实例。它检查的是对象的原型链。
[] instanceof Array // true
{} instanceof Object // true
new Date() instanceof Date // true 这种方法可以返回对象的内部属性[[Class]],从而准确地判断对象的类型。
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]" 这是一个专门用来检查是否为数组的方法。
Array.isArray([]) // true
Array.isArray({}) // false 可以通过typeof判断是否是对象类型,再结合instanceof判断是否是特定的对象类型。
function isFunction(value) {
return typeof value === 'function';
}
function isObject(value) {
return typeof value === 'object' && value !== null;
}
function isArray(value) {
return Array.isArray(value);
}
// 示例用法
isFunction(function() {}); // true
isObject({}); // true
isArray([]); // true这些方法可以根据具体的需求来选择使用。