ES2015 (ES6) 新增的方法
fil方法实际上是要报下标范围来给范围内的元素覆盖新的值
参数
- value
- 不填为undefined
- start
- 默认0,undefind取默认值
- 其值会经过
>>0
处理,保证为数字
- end
- 默认length-1,undefind取默认值
- 其值会经过
>>0
处理,保证为数字 ```javascript const arr = [1, 2, 3, 4, 5];
// [2, 4) const newArr = arr.fill(‘a’, 2, 4); // [1, 2, ‘a’, ‘a’, 5]; const newArr = arr.fill(‘b’, 2, 5); // [1, 2, ‘b’, ‘b’, ‘b’]; const newArr = arr.fill(‘c’, 2); // [1, 2, ‘c’, ‘c’, ‘c’]; const newArr = arr.fill(‘d’); // [‘d’, ‘d’, ‘d’, ‘d’, ‘d’];
// start, end为负数 // [-4 + length, -2 + length) // [1, 3) const newArr = arr.fill(‘e’, -4, -2);
// 全部覆盖undefined const newArr = arr.fill() // [undefined, undefined, undefined, undefined, undefined]
// start === end 不变 const newArr = arr.fill(‘f’, 1, 1);
// newArr就是原数组的引用 arr === newArr // true
<a name="B3IXC"></a>
# 借助fill创建类数组方法
```javascript
function makeArrayLike (arr) {
var arrLike = {
length: arr.length,
push: [].push,
splice: [].splice
}
arr.forEach(function(item, index){
[].fill.call(arrLike, item, index, index + 1);
});
return arrLike;
}
polyfill
Array.proptype.myFill = function(){
var value = arguments[0] || undefined,
start = arguments[1] >> 0,
end = arguments[2] >> 0;
if(this == null){
throw new TypeError('This is null or not defined');
}
var obj = Object(this),
len = obj.length >>> 0;
start = start < 0 ?
Math.max(len + start, 0) :
Math.min(start, len);
end = end === undefined ?
len:
end >> 0;
end = end < 0 ?
Math.max(len + end, 0) :
Math.min(end, len);
while (start < end){
obj[start] = value;
start ++;
}
return obj;
}