1. 数组检测
_.isArray = function(array){
return toString.call(array) === "[object Array]"
}
2. 各个类型检测
var types = ["Function", "String", "Object", "Number", "Boolean"]
_.each(types, function(name) {
_["is" + name] = function(obj) {
return toString.call(obj) === "[object " + name + "]";
}
});
3. 获取一个对象的keys
var hasEnumbug = ({
toString: null
}).propertyIsEnumerable("toString");
var list = ["hasOwnProperty", "constructor", "isPrototypeOf", "propertyIsEnumerable", "toLocaleString", "toString",
"valueOf"
];
_.keys = function(obj) {
var result = [];
var name, prop;
//判断是不是对象
if (!_.isObject(obj)) {
return [];
}
//Object是否有着keys方法
if (Object.keys) {
return Object.keys(obj);
}
//如果没有keys方法,则遍历所有属性,然后返回数组
for (name in obj) {
result.push(name);
}
//解决IE9 以下的bug
if (!hasEnumbug) {
for (var i = 0; i < list.length; i++) {
prop = list[i];
if (obj[prop] !== Object.prototype[prop]) {
result.push(prop);
}
}
}
return result;
}
- undefined的表示
void 0
来表示undefined
网友评论