首页 > 数组方法fill():[].fill.call({ length: 3 }, 4);

数组方法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 对象上,比如 NodeListHTMLCollection 等,即使那些类没有实现类似的方法——只要那些类实现了 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]);
    }
};
【热门文章】
【热门文章】