这篇文章给大家分享的是有关JavaScript中怎样判断一个值的类型的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
我们知道在js中有一个运算符可以帮助我们判断一个值的类型,它就是typeof运算符。
console.log(typeof 123); //number
console.log(typeof '123'); //string
console.log(typeof true); //boolean
console.log(typeof undefined); //undefined
console.log(typeof null); //object
console.log(typeof []); //object
console.log(typeof {}); //object
console.log(typeof function() {}); //function
我们从以上结果可以看出typeof的不足之处,它对于数值、字符串、布尔值分别返回number、string、boolean,函数返回function,undefined返回undefined,除此以外,其他情况都返回object。
所以如果返回值为object,我们是无法得知值的类型到底是数组还是对象或者其他值。为了准确得到每个值的类型,我们必须使用js中另一个运算符instanceof。下面简单的说一下instanceof的用法。
instanceof运算符返回一个布尔值,表示指定对象是否为某个构造函数的实例。
instanceof运算符的左边是实例对象,右边是构造函数。它会检查右边构造函数的ptototype属性,是否在左边对象的原型链上。
var b = [];
b instanceof Array //true
b instanceof Object //true
注意,instanceof运算符只能用于对象,不适用原始类型的值。
所以我们可以结合typeof和instanceof运算符的特性,来对一个值的类型做出较为准确的判断。
//得到一个值的类型
function getValueType(value) {
var type = '';
if (typeof value != 'object') {
type = typeof value;
} else {
if (value instanceof Array) {
type = 'array';
} else {
if (value instanceof Object) {
type = 'object';
} else {
type = 'null';
}
}
}
return type;
}
getValueType(123); //number
getValueType('123'); //string
getValueType(true); //boolean
getValueType(undefined); //undefined
getValueType(null); //null
getValueType([]); //array
getValueType({}); //object
getValueType(function(){}); //function
感谢各位的阅读!关于“JavaScript中怎样判断一个值的类型”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。