手写Array.prototype.map
Array.prototype.my_map = function (fn, context) {
if (Object.prototype.toString.call(fn) != "[object Function]") {
throw new TypeError(fn + " is not a function");
}
const ctx = context ? context : this;
const thisArray = this;
let resArr = []
for (var i = 0; i < thisArray.length; i++) {
resArr.push(fn.call(ctx, thisArray[i], i, thisArray));
}
return resArr // 返回map后的数组
}
// 测试用例
var a = [1, 2, 3];
var b = a.my_map(function (val, index) {
return val + 1;
})
console.log(b);
手写Array.prototype.forEach
Array.prototype.my_forEach = function (fn, context) {
if (Object.prototype.toString.call(fn) != "[object Function]") {
throw new TypeError(fn + " is not a function");
}
const ctx = context ? context : this;
const thisArray = this;
for (var i = 0; i < thisArray.length; i++) {
fn.call(ctx, thisArray[i], i, thisArray)
}
}
手写Array.prototype.some
Array.prototype.my_some = function (fn, context) {
if (Object.prototype.toString.call(fn) != "[object Function]") {
throw new TypeError(fn + " is not a function");
}
const ctx = context ? context : this;
const thisArray = this;
for (var i = 0; i < thisArray.length; i++) {
const result = fn.call(ctx, thisArray[i], i, thisArray);
if (result) return true
}
return false
}
手写Array.prototype.every
Array.prototype.my_every = function (fn, context) {
if (Object.prototype.toString.call(fn) != "[object Function]") {
throw new TypeError(fn + " is not a function");
}
const ctx = context ? context : this;
const thisArray = this;
for (var i = 0; i < thisArray.length; i++) {
const result = fn.call(ctx, thisArray[i], i, thisArray);
if (!result) return false
}
return true
}
网友评论