检测原始值、引用值和属性

一、原始值
javascript中包含5种原始类型:字符串、数字、布尔值、null和undefined。
判断一个值得最佳选择是typeof运算符,返回一个表示值得类型的字符串。
字符串            string
数字               number
布尔值            boolean
undefined       undefined

例如:

if(typeof name === "string"){
   console.log("name的值是字符串");  
}

 

二、引用值
javascript中包含几种内置的引用类型:Object、Array、Date和Error。
判断是否为引用类型最佳选择instanceof运算符。
默认情况下,每个对象都会继承Object,因此每个对象的value instanceof Object都会返回true。

例如:

if(val instanceof Date){
   console.log("是Date的对象。");  
}



三、检测函数
使用typeof运算符。

例如:

function test(){}
if(typeof test === "function"){
  console.log("test是函数");
}


备注:IE8及其一下版本,将typeof document.getElementById认为是Object,而不是function。

四、检测数组

例如:

function isArray(){
  return Object.prototype.toString.call(arguments[0])  === '[object Array]'; 
}

 

备注:引用值和判断数组方法最大的区别在于frame中,instanceof Array在frame中不能返回真确的结果,原因是每个frame都有各自的Array构造函数,因此一个frame中的实例在另外一个frame中不会识别。


五、检测属性
判断属性是否存在最好的方法是使用in运算符。
如果只想检查实例对象的某个属性是否存在,则使用hasOwnProperty()方法。

例如:

if('placeholder' in document.createElement('input')){
  console.log("支持placeholder属性");
}

 

if(document.createElement('input').hasOwnProperty("placeholder")){
  console.log("true。备注:判断DOM元素是否具有某种属性,慎用hasOwnProperty()方法");
}


备注:判断DOM元素是否具有某种属性,慎用hasOwnProperty()方法。
IE8及其以下版本认为DOM元素并非继承自Object。



posted @ 2013-07-21 23:05  前端咖  阅读(563)  评论(0编辑  收藏  举报