function each(item, fn) {
if (Array.prototype.forEach) {
// 若支持forEach方法
item.forEach(fn)
} else {
// 不支持forEach的时候 便遍历并执行
for (var i in item) {
fn(i, item[i])
console.log(i);
}
}
}
var arr = ['java', 'c', 'php', 'html']
function output(item, index) {
console.log(item);
console.log(index + ': ' + item)
}
each(arr, output)
这里的output即为fn的实参,而fn 中i 和item[i]分别为第一参数和第二参数,不应该是对应
output里面的item 和index 吗?但是如果是这样,output里面的item 和index 不应该调换
位置吗?最终调试是上面代码是正确的,但是实在想不通,求助
js中数组的foreach方法,第一个参数是遍历的元素,第二个是索引,第三个是数组本身.
箭头所指的这里,你的写法是有问题的,和js中数组foreach方法参数不同.
应该改为
另外,js中的数组,不推荐使用for...in遍历,具体百度
另外,jquery的each方法,第一个是索引,第二个参数是遍历的元素,你是不是把jquery和js的foreach参数给搞混了?