Heim  >  Artikel  >  Web-Frontend  >  js中将具有数字属性名的对象转换为数组_javascript技巧

js中将具有数字属性名的对象转换为数组_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:09:391135Durchsuche

虽然不太常用,但我们的确可以给对象添加以数字为属性名的属性:

复制代码 代码如下:

var obj = {};
obj[0] = 1;
obj[1] = 2;

这个对象并不是数组类型,那有没有办法把它转换为数组类型呢?jQuery代码中采用了Array.prototype.slice把这种对象转换为数组,但我试了好几遍,就是不行:
复制代码 代码如下:

var obj = {};
obj[0] = 1;
obj[1] = 2;
alert(Array.prototype.slice.call(obj));

上面这段代码在IE下直接报错,在Firefox下虽然没有报错,输出内容却是空。也就说,转换失败了。这种内置方法的问题最好还是查查ECMA-262,slice方法的执行流程的前两步如下:
复制代码 代码如下:

1. Let A be a new array created as if by the expression new Array().
2. Call the [[Get]] method of this object with argument "length".

这里提到了参数length。obj对象虽然有数字索引,但是却没有length属性。其实问题就在这:slice方法不知道这个对象的长度。简单修改一下代码,添加length属性:
复制代码 代码如下:

var obj = {};
obj[0] = 1;
obj[1] = 2;
obj.length = 2;
alert(Array.prototype.slice.call(obj));

输出内容是"1,2",复制成功。那是不是说明,只要调用slice方法的this有数字索引和length属性,就可以转换为数组呢?。

这个定律在大部分浏览器下成立。然而,在IE环境下,对于HtmlCollection这样的DOM元素集合,即使具有上述特征,它在调用slice的时候也会报错。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn