日期:2014-05-16 浏览次数:20427 次
/**
?* 判断一个对象是否是类数组
?* @param o
?*/
function isArrayLike(o) {
??? //如果是Array构造的一个实例,那肯定就是了
??? if (o instanceof Array)return true;
??? //如果连length属性都没有,那肯定不是了,举例:arguments参数有length属性
??? if (!"length" in o)return false;
??? //如果,是用户自定义的length,那么需要判断他的类型
??? if (typeof o.length != "number")return false;
??? if (o.length < 0)return false;
??? if (o.length > 0) {
??????? if (!(o.length - 1) in o)return false;? //这行不是很理解,有知道的吗?
??? }
??? /**
???? * 最后需要把方法排除在外
???? * 此行注释去掉,则isArrayLike(MyFunc)=false
???? */
??? //??? if (typeof(o) == "function")return false;
??? return true;
}
function MyFunc(x, y, a, b, c) {
??? this.x = x;
??? this.y = y;
??? return this;
}
var f = new MyFunc(3, 5);
document.writeln(MyFunc.length);//5
//分明是一个function,为什么成了Array Like?
document.writeln(isArrayLike(MyFunc));//true
document.writeln(isArrayLike(f));//false
document.writeln("<br/>");
var MyMap = {
??? x:"sjkfdks",
??? y:"3223",
??? z:88,
??? length:Math.random() //长度不是整数也可以?呵呵
}
document.writeln(MyMap.length);//6
document.writeln(isArrayLike(MyMap));//true
document.writeln("<br/>");
var ret = [];
ret['x'] = 32;
ret['y'] = 33;
ret['z'] = 35;
document.writeln(ret.length);
document.writeln(isArrayLike(ret));
document.writeln("<br/>");
ret = [];
ret.x = 32;
ret.y = 33;
ret.z = 35;
document.writeln(ret.length);
document.writeln(isArrayLike(ret));
document.writeln("<br/>");
function test(a, b, c) {
??? document.writeln(isArrayLike(arguments));
}
test(2, 3, 4, 5);