"```markdown
实现一个数组的 fill 方法
JavaScript 中的 Array.prototype.fill() 方法用于用一个静态值填充数组中的所有元素,通常接受三个参数:要填充的值、填充的起始索引和结束索引。下面是对该方法的一种实现方式。
Array.prototype.myFill = function(value, start = 0, end = this.length) {
// 处理负索引
const length = this.length;
let k = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
let final = end < 0 ? Math.max(length + end, 0) : Math.min(end, length);
// 用 value 填充数组
while (k < final) {
this[k] = value;
k++;
}
return this;
};
代码解释
-
原型扩展: 我们在
Array.prototype上添加myFill方法,使其可以在所有数组实例上使用。 -
默认参数:
start和end参数的默认值分别为 0 和数组的长度。 -
处理负索引: 负索引需要转换为正索引。对于
start,我们使用Math.max确保它不会小于 0,使用Math.min确保它不会超过数组长度。对end做同样的处理。 -
填充逻辑: 通过一个
while循环,逐个将值赋给数组中的元素。 -
返回数组: 最后返回填充后的数组,以便链式调用。
示例用法
以下是使用 myFill 方法的示例:
const arr = [1, 2, 3, 4, 5];
// 完全填充数组
console.log(arr.myFill(0)); // [0, 0, 0, 0, 0]
// 从索引 1 开始填充
console.log(arr.myFill(7, 1)); // [0, 7, 7, 7, 7]
// 从索引 1 到 3 填充
console.log(arr.myFill(8, 1, 3)); // [0, 8, 8, 7, 7]
注意事项
- 如果
start大于或等于end,则不会填充任何元素。 - 此实现不会对数组的原始
fill方法进行覆盖,只是提供了一个自定义实现。 - 可以根据需要进一步扩展该方法,例如支持填充特殊对象或深度填充。
通过提供的 myFill 方法,我们可以方便地实现数组填充效果,符合原生 fill 方法的行为。
"