javascript - 数组方法fill():[].fill.call({ length: 3 }, 4);
本文介绍了javascript - 数组方法fill():[].fill.call({ length: 3 }, 4);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}
怎么是这样的结果
解决方案
首先,我 assume 你知道 Array.prototype.call
是什么意思。
我可以这么实现 myFill
:
Array.prototype.myFill = function (content) {
var i;
for (i = 0; i < this.length; i++) {
this[i] = content;
}
return this;
};
然后你会发现它的行为和 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
里面的方法就不止可以用到 Array
实例上,也可以用到其它 array-like 对象上,比如 NodeList
和 HTMLCollection
等,即使那些类没有实现类似的方法——只要那些类实现了 length
属性就行。
举例:document.getElemenetsByTagName('div')
返回一个 HTMLCollection
对象,而那个对象是没有 forEach
方法的。于是 document.getElementsByTagName('div').forEach
是不存在的。
但是 HTMLCollection
对象有 length
属性。于是我就可以 [].forEach.call(document.getElementsByTagName('div'), 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]);
}
};
这篇关于javascript - 数组方法fill():[].fill.call({ length: 3 }, 4);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文