这里只拿arguments这个伪数组作为演示
// 获取arguments
function aa(){
console.log(arguments); // 输出 Arguments(5) [1, 2, 3, 4, 5, callee: ƒ, Symbol(Symbol.iterator): ƒ] 伪数组,因为它的__proto__: Object 指向Object而非Array
// Array.prototype.forEach.call()
// call前面接一个函数方法,用于改变该方法的this值
Array.prototype.forEach.call(arguments,(item,index)=>{
console.log(item); //遍历输出分别为1 2 3 4 5
})
}
aa(1,2,3,4,5);
为什么这样写是对的呢?
我们来先说说forEach的遍历原理吧,首先forEach是在Array原型链上的一个函数,可调出来用。用法是[1,2,3,4].forEach()。是数组[1,2,3,4]调用了forEach这个方法,在forEach方法内部的this就指向这个数组,再将该数组通过for遍历的给回调函数参数item、index和array,实为arguments[0]、arguments[1]、arguments[2],用于用户在回调函数中调出。
353

被折叠的 条评论
为什么被折叠?



