Javascript类型判断
typeof 运算符的结果值
numberstringbooleanundefinedfunctionobjectsymbolES6新增
var fun = function(){};
var obj = {};
var sym = Symbol();
typeof true // boolean
typeof 1 // number
typeof a // undefined
typeof 'abc' // string
typeof fun // function
typeof sym // symbol
typeof [] // object
typeof {} // object
typeof null // object
typeof 运算符产生的值有 number、string、boolean、undefined、function、object和Symbol 7种类型。而对于array、null类型,typeof 都判断为object。如何区别array、null、object。
isNull
判断null 类型相对简单。
var isNull = function(value){
return value === null;
};
isNull(null) // true
isArray
区别数组和对象,可以通过自定义isArray方法。
var isArray = function(value){
return Object.prototype.toString.apply(value) === '[object Array]';
};
这个方法有个缺陷,就是在识别不同的window或者iframe里构造的数组时会失败。
示例:
父页面存放一个全局变量arr
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var arr = [1,2,3];
</script>
<iframe src="/child"></iframe>
</body>
</html>
子页面获取数组arr后调用isArray方法返回false。
var arr = window.parent.arr;
var isArray = function(value){
return value &&
typeof value === 'object' &&
value.constructor === Array;
};
console.log(isArray(arr)); // false
更好的判断数组方法
var isArray = function(value){
return Object.prototype.toString.apply(value) === '[object Array]';
};
var arr = window.parent.arr;
var isArray = function(value){
return Object.prototype.toString.apply(value) === '[object Array]';
};
console.log(isArray(arr)); // true
924

被折叠的 条评论
为什么被折叠?



