foreach和map都是ES6中新数组处理方法,对于这些方法死记硬背的效率是很低的,因此我们通过尝试用原生的js实现一个foreach和一个map
原生JavaScript实现foreach
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
foreach有两个参数,分别是一个回调函数和一个用于指定this的参数,其中回调函数的三个参数是数组的每一项,每一项的索引以及数组本身。他本质上是一个语法糖,利用循环让数组的每个参数都执行我们的回调函数
`Array.prototype.myforEach = function(callback, thisArg = this) { //将函数挂载到Array的原型链上
if (typeof callback != 'function') { //首先检测回调函数的类型,如果不是函数抛出异常
throw new TypeError(callback + "is not a function");
}
if (this == undefined) { //如果this没有指向任何对象,抛出异常
throw new TypeError("this is null or not undefined");
}
const o = Object(this) //保证this是一个对象,拥有可遍历的属性,
//这里的this可以是任何对象,String,Array,Object 都可以
//这里其实也可以对this提前处理成数组,但考虑到后期可能会用参数绑定其他的this
//因此考虑到可扩展性可以转化为拥有可以遍历的Object
// const o = Array.from(this);
const len = o.length;
let k = 0;
while (k < len) { //循环遍历,用回调函数处理数组中的每一项
if (k in o) { //确保k是一个可以遍历到的对象或者没有出现下标越界的情况
callback.call(thisArg, o[k], k, o) //绑定this并指定回调函数
//注意foreach是没有返回值的,每一项会作为参数执行回调函数
}
k++;
}
}`
原生JavaScript实现map
map的原理跟froeach差不多,但区别是map不会改变数组本身,而是返回一个新数组,返回的新数组的每一项是原数组执行回调函数后对应的结果,基本思路跟foreach差不多,但要在内部定义一个数组并返回
`Array.prototype.myMap = function(callback, thisArg = this) {
if (typeof callback != 'function') {
throw new TypeError(callback + "is not a function");
}
if (this == undefined) {
throw new TypeError("this is null or not undefined");
}
let res = [];
const o = Object(this)
// const o = Array.from(this);
const len = o.length;
for (let i = 0; i < len; i++) {
if (i in o) {
res[i] = callback.call(thisArg, o[i], i, o)
}
}
return res;
}`