避免“空比较”
避免与null进行比较,因为与null比较并不能真正的避免错误的发生,返回的值有可能是字符串或数字,甚至可能是任意对象,之后方法就可能会出现一些错误。
// 这是不好的写法
var controller = {
process:function(items){
if(items !== null)
{
items.sort();
items.forEach(function(item){
//dosomething();
})
}
}
}
1.检测原始值
使用typeof
字符返回 “string"
数字返回 "number"
布尔值返回 "boolean"
undefined返回 “undefined”
语法
typeof variable
typeof(varibale)
2.检测引用值
但是typeof并不是万能的,它只能用来检测原始值,object,array,date,error这些引用值就无法识别,这些类型返回的都是object,这样就出现问题了。
所以检测引用值则使用instanceof
语法
value instance constructor
例子
if(value instanceof Date)
{
console.log(value.getFullYear());
}
if(value instanceof RegExp)
{
if(value.test(anotherValue))
{
console.log('matches')
}
}
if(value instanceof Error)
{
throw value;
}
然而还需要注意,因为每个对象都是继承object,所以…………value instance Object 都会返回true
var now = new Date();
console.log(now instanceof Object); // true
console.log(now instanceof Date); // true
自定义类型检测
function Person(name){
this.name = name;
}
var name = Person('name');
console.log(name instanceof Object);//true
console.log(name instanceof Person);//true
如何检测函数和数组额外说
2.1检测函数
javascript中函数属于引用类型,所以可以这样
function myFunction(){}
console.log(myFunc instanceof Function);//true
但是方法不可以跨帧使用,因为每个帧都有各自的Function构造函数。好在typeof运算符可以用于函数,返回’function’ 所以……
function myFunc(){}
console.log(type myFunc === “function”);//true
这样就可以避免无法跨帧的问题。
2.2数组检测
“鸭式辨法”
数组是唯一包含sort()方法的对象,那么就可以通过检测sort()方法是否存在来判定是不是array类型了
function isArray(arr){
return typeof arr.sort() === "function";
}
Kangax提出的方案
function isArray(value)
{
return Object.prototype.toString.call(value) === '[object Array]';
}
Array.isArray()也可以检测一个值是否是一个数组
function isArray(value)
{
if (typeof Array.isArray() === 'function')
{
return Array.isArray(value);
} else {
return Object.prototype.toString.call(value) === '[object Array]'
}
}
3.检测属性
检测一个属性是否在对象中存在
var object = {
count:'0',
relate:null
}
if ("count" in object)
{
//dosomething
}
if ("relate" in object)
{
//dosomething
}
如果只是都想知道属性是否在对象里,使用hasOwnProperty()
//所有非dom对象
if (object.hasOwnProperty("relate")){
//dosomething
}
//不确定是不是dom对象
if ("hasOwnProperty" in object && object.hasOwnProperty("relate")){
//dosomething
}
大致以上这些,有错误和不足的地方帮忙纠正下。:cold_sweat: