用法
1.forEach只能用于数组,数组遍历
2.可以传两个参数,第一个参数必须传,是function(ele, index, self)
ele代表数组中的数据,index代表索引,self代表数组本身。第二个参数可有可无,改变this指向
举个栗子
var arr = [
{
province:'重庆',
city:'重庆'
},
{
province:'北京',
city:'北京'
},
{
province:'四川',
city:'成都'
}
];
arr.forEach(function(ele, index, self){
console.log(ele, index, self, this);
},arr);
我们来看输出结果
再打开一项看看
自己重写forEach方法
Array.prototype.myForEach = function (func) {
var _this = this,
len = _this.length,
param2 = arguments[1] || window;
for (var i = 0; i < len; i++){
func.apply(param2,[_this[i], i, _this]);
}
}
arr.myForEach(function (ele, index, self) {
console.log(ele, index, self, this);
}, arr);
效果和forEach一样