更新时间: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这些方法可以根据具体的需求来选择使用。
AI鸿蒙原生智能正式版课程,培养全端跨平台鸿蒙工程师
2026-03-10AI鸿蒙原生智能正式版课程,培养全端跨平台鸿蒙工程师
2026-03-10毕业16个工作日,平均薪资13180元,就业率100%,广州黑马AI智能应用开发(Java)学科20250529班
2026-03-06毕业32个工作日,平均薪资11147元,就业率95%,广州黑马AI智能应用开发(Java)学科20250326班
2026-03-05黑马程序员2025全国就业数据发布:全学科平均就业率92.07%,AI开发类就业平均薪资达11869.67元。
2026-03-05黑马全国校区齐开班!场面太太太壮观了!
2026-03-03