更新时间: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设计】北京143期毕业仅36天,全员拿下高薪offer!黑马AI设计连续6期100%高薪就业
2025-09-19【跨境电商运营】深圳跨境电商运营毕业22个工作日,就业率91%+,最高薪资达13500元
2025-09-19【AI运维】郑州运维1期就业班,毕业14个工作日,班级93%同学已拿到Offer, 一线均薪资 1W+
2025-09-19【AI鸿蒙开发】上海校区AI鸿蒙开发4期5期,距离毕业21天,就业率91%,平均薪资14046元
2025-09-19【AI大模型开发-Python】毕业33个工作日,就业率已达到94.55%,班均薪资20763元
2025-09-19【AI智能应用开发-Java】毕业当天offer率91%,薪资1W+占比54.2%,班级均薪12k+
2025-09-19