typeof和constructor联合使用 判断变量是否为数组或日期

我们知道typeof可以用来查看变量的数据类型,比如:
typeof "John"                 // 返回 string 
typeof 3.14                   // 返回 number
typeof NaN                    // 返回 number
typeof false                  // 返回 boolean
typeof [1,2,3,4]              // 返回 object
typeof {name:'John', age:34}  // 返回 object
typeof new Date()             // 返回 object
typeof function () {}         // 返回 function
typeof myCar                  // 返回 undefined (如果 myCar 没有声明)
typeof null                   // 返回 object


        从上述例子中不难发现,数组、对象、日期的类型都是object,那么,在不知道的情况下如何确定获取到的数据到底是数组还是对象或日期呢?这里就要用到constructor属性了。

constructor用来返回所有js变量的构造函数,如:
"John".constructor                 // 返回函数 String()  { [native code] }
(3.14).constructor                 // 返回函数 Number()  { [native code] }
false.constructor                  // 返回函数 Boolean() { [native code] }
[1,2,3,4].constructor              // 返回函数 Array()   { [native code] }
{name:'John', age:34}.constructor  // 返回函数 Object()  { [native code] }
new Date().constructor             // 返回函数 Date()    { [native code] }
function () {}.constructor         // 返回函数 Function(){ [native code] }


        由此,我们可以写两个方法去判断一个变量是否是数组:

function isArray(myArray){
    return myArray.constructor.toString().indexOf('Array') != -1;
}
        同理,也可以判断一个变量是否为日期:
function isDate(myDate){
    return myDate.constructor.toString().indexOf('Date') != -1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值