// 手写Array.map方法
Array.prototype.map2 = function(callback, args) {
if(typeof callback !== 'function') {
throw new TypeError('callback is not a function')
}
let oldArr = Object.values(this)
// 此时的this指向调用该方法的数组的对象
let len = oldArr.length;
let i = 0, res = []
while(i < len) {
res[i] = callback.call(this, oldArr[i])
i++;
}
return res
}
// 手写Array.filter方法
Array.prototype.filter2 = function(callback, args) {
if(typeof callback !== 'function') {
throw new TypeError('callback is not a function')
}
let oldArr = Object(this)
let k = 0, res = [], len = oldArr.length
while (k < len) {
callback.call(this, oldArr[k]) && (res.push(oldArr[k]));
k++
}
return res
}
// 手写Array.find方法
Array.prototype.find2 = function(callback, args) {
if(typeof callback !== 'function') {
throw new TypeError('callback is not a function')
}
let oldArr = Object(this)
let k = 0, len = oldArr.length, res
while (k < len) {
if( callback.call(this, oldArr[k])) {
res = oldArr[k];
break;
}
k++
}
return res
}
// 手写Array.some方法,判断是否存在满足条件的元素
Array.prototype.some2 = function(callback, args) {
if(typeof callback !== 'function') {
throw new TypeError('callback is not a function')
}
let oldArr = Object(this)
let k = 0, len = oldArr.length, res = false
while (k < len) {
if( callback.call(this, oldArr[k])) {
res = true;
break;
}
k++
}
return res
}
// 手写Array.reduce方法
Array.prototype.reduce2 = function(callback, initVal) {
if(typeof callback !== 'function') {
throw new TypeError('callback is not a function')
}
let oldArr = Object(this)
let k = 0, len = oldArr.length, res;
if(arguments.length > 1 ) {
// 存在初始值,
res = initVal
} else {
// 无初始值,则初始为数组的第一个元素
if(!oldArr.length) {
throw new TypeError('Reduce of empty array with no initial value')
}
res = oldArr[0]
k++ // 数组下标从1开始
}
while (k < len) {
res = callback(res, oldArr[k], k, oldArr)
k++
}
return res
}
var arr = [{id: 1, name: '张三'},{id: 2,name:'李四'}, {id: 1, name: '王二'}]
// var arr2 = arr.map2(function(ele) {
// return {
// id2: ele.id,
// name2: ele.name
// }
// })
// console.log(arr2);
// var arr3 = arr.filter2(ele => ele.id === 5)
// console.log(arr3);
// var arr4 = arr.find2(ele => ele.id === 5)
// console.log(arr4);
// var arr5 = arr.some2(ele => ele.id === 6)
// console.log(arr5);
var nums = [1,2,3,4,5]
var sum = nums.reduce2(function(pre,cur,index,arr) {
return pre + cur;
}, 100)
console.log(sum);
手写数组中常用的ES6方法
最新推荐文章于 2024-02-07 10:46:14 发布