YUI的构建数组,将类数组转换成真正的数组,从而可以使用数组的所有方法
数组构建 //真正的数组返回1,类数组返回2,其余的返回0
YArray.test = function (obj) {
var result = 0;
if (Lang.isArray(obj)) {
result = 1;
} else if (Lang.isObject(obj)) {
try {
// indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here),
// or functions without apply/call (Safari
// HTMLElementCollection bug).
if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) {
result = 2;
}
} catch (ex) {}
}
return result;
};
Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; //thing 要构建数组的元素 startIndex 从thing中的第几个开始构建数组 force强制转换数组,thing将会当成一个类数组
//Note: elements that are also collections, such as `<form>` and `<select>`
//elements, are not automatically converted to arrays. To force a conversion,
//pass `true` as the value of the _force_ parameter.
function YArray(thing, startIndex, force) {
var len, result;
/*jshint expr: true*/
startIndex || (startIndex = 0);
if (force || YArray.test(thing)) {
//IE8及以下的会报错,thing在这里是NodeList对象,不是javascript对象,在现代浏览器已除去这个限制
try {
return Native.slice.call(thing, startIndex);
} catch (ex) {
result = [];
for (len = thing.length; startIndex < len; ++startIndex) {
result.push(thing[startIndex]);
}
return result;
}
}
return [thing];
}
Y.Array = YArray;
var aA = document.getElementsByTagName(‘a’)
var html = document.getElementsByTagName(‘html’)[0]
YArray(aA) ==> 传入一个类数组,产生一个真正的数组
YArray(html) ==> 传入一个对象,产一个数组
YArray(1,2,3,4,5) ==> 传入一系列的值,产生一个空的数组
YArray(1,0,0,0) ==> 如果第三个参数为假,则产生[第一个参数]的数组
a. ‘length’ in obj 与length in obj的区别
在数组中这两个没有区别
在对象中这两个有区别,'length'表示obj中有'length'这一个键,length表示obj的属性,因此 'length’ in window ==> true 而 length in window ==> false