Ruby's Louvre

每天学习一点点算法

导航

ES6中新添加的Array.prototype.fill

用法

array.fill(start=0, end=this.length)

示例

[1, 2, 3].fill(4)            // [4, 4, 4]
[1, 2, 3].fill(4, 1)         // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2)      // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1)      // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2)    // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN)  // [4, 4, 4]
[].fill.call({length: 3}, 4) // {0: 4, 1: 4, 2: 4, length: 3}

向前兼容方案

if (![].fill) {
  Array.prototype.fill = function(value) {

    // Steps 1-2.
    var O = Object(this);

    // Steps 3-5.
    var len = parseInt(O.length);

    // Steps 6-7.
    var relativeStart = parseInt(arguments[1] || 0);

    // Step 8.
    var k = relativeStart < 0
            ? Math.max(len + relativeStart, 0)
            : Math.min(relativeStart, len);

    // Steps 9-10.
    var relativeEnd = parseInt(arguments[2] || len);

    // Step 11.
    var final = relativeEnd < 0
                ? Math.max(len + relativeEnd, 0)
                : Math.min(relativeEnd, len);

    // Step 12.
    for (; k < final; k++) {
        O[k] = value;
    }

    // Step 13.
    return O;
  };
}

相关链接

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array.prototype.fill()

posted on 2014-04-12 08:17  司徒正美  阅读(3430)  评论(0编辑  收藏  举报