扫码关注官方订阅号
[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}
怎么是这样的结果
人生最曼妙的风景,竟是内心的淡定与从容!
首先,我 assume 你知道 Array.prototype.call 是什么意思。
Array.prototype.call
我可以这么实现 myFill:
myFill
Array.prototype.myFill = function (content) { var i; for (i = 0; i < this.length; i++) { this[i] = content; } return this; };
然后你会发现它的行为和 fill 是一样的:
fill
[1, 2, 3].myFill(4); // [4, 4, 4] [].myFill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}
所以说明原本的 Array.prototype.fill 采取的就是类似的实现。
Array.prototype.fill
那么为什么要那么实现呢?因为这么实现的话,Array.prototype 里面的方法就不止可以用到 Array 实例上,也可以用到其它 array-like 对象上,比如 NodeList 和 HTMLCollection 等,即使那些类没有实现类似的方法——只要那些类实现了 length 属性就行。
Array.prototype
Array
NodeList
HTMLCollection
length
举例:document.getElemenetsByTagName('p') 返回一个 HTMLCollection 对象,而那个对象是没有 forEach 方法的。于是 document.getElementsByTagName('p').forEach 是不存在的。
document.getElemenetsByTagName('p')
forEach
document.getElementsByTagName('p').forEach
但是 HTMLCollection 对象有 length 属性。于是我就可以 [].forEach.call(document.getElementsByTagName('p'), function (el) { el.style.background = '#F00'; });。而这之所以能实现,就是因为 Array.prototype.forEach 的实现类似于:
[].forEach.call(document.getElementsByTagName('p'), function (el) { el.style.background = '#F00'; });
Array.prototype.forEach
Array.prototype.myForEach = function (callback) { var i; for (i = 0; i < this.length; i++) { callback(this[i]); } };
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
首先,我 assume 你知道
Array.prototype.call是什么意思。我可以这么实现
myFill:然后你会发现它的行为和
fill是一样的:所以说明原本的
Array.prototype.fill采取的就是类似的实现。那么为什么要那么实现呢?因为这么实现的话,
Array.prototype里面的方法就不止可以用到Array实例上,也可以用到其它 array-like 对象上,比如NodeList和HTMLCollection等,即使那些类没有实现类似的方法——只要那些类实现了length属性就行。举例:
document.getElemenetsByTagName('p')返回一个HTMLCollection对象,而那个对象是没有forEach方法的。于是document.getElementsByTagName('p').forEach是不存在的。但是
HTMLCollection对象有length属性。于是我就可以[].forEach.call(document.getElementsByTagName('p'), function (el) { el.style.background = '#F00'; });。而这之所以能实现,就是因为Array.prototype.forEach的实现类似于: