forEach()
方法对数组的每个元素执行一次提供的函数。(ES5)
// 求和
function sum(...arg) {
let sumNumber = 0;
arg.forEach((eve) => {
sumNumber += eve;
});
return sumNumber
}
console.log(sum(1, 2, 3));
forEach描述:
第一个参数是callback回调函数;
里面有三个参数:
第一个参数是ele:数组的值
第二个参数是index:下标值
第三个参数是arr:正在执行的当前数组
第二个参数是thisArg,默认为this指向window
<script>
/*
forEach():
第一个参数是callback回调函数;
里面有三个参数:
第一个参数是ele:数组的值
第二个参数是index:下标值
第三个参数是arr:正在执行的当前数组
第二个参数是thisArg,默认为this指向window
*/
const arr = [
{ name: '张三', age: 21 },
{ name: '李四', age: 22 },
{ name: '王五', age: 23 },
];
let obj = {
naem: 'xyz'
}
function deal(ele, index, curArr) {
console.log(ele, index, curArr, this)
}
arr.forEach(deal)
arr.forEach(deal, obj)
</script>
result:
通过源码实现forEach方法:
//通过源码实现forEach方法
const arr = [
{ name: '张三', age: 21 },
{ name: '李四', age: 22 },
{ name: '王五', age: 23 },
];
Array.prototype.myForEach = function (func) {
let _this = arguments[1] != undefined ? arguments[1] : window;
for (let i = 0; i < this.length; i++) {
func.apply(_this, [this[i], i, this])
}
}
let obj = {
naem: 'xyz'
}
function deal(ele, index, curArr) {
console.log(ele, index, curArr, this)
}
arr.myForEach(deal)
arr.myForEach(deal, obj)
result: