IE真是让前端开发者头疼的问题,在解决数组的迭代的过程中,IE8及以下并不能很好的支持。于是去网上搜了搜数组迭代中的every方法,在一个博客大V中搬过来后,发现仍会报错,又比对了下网上的代码,发现我复制的并没有错(QAQ 也不试试就直接用放到博客,这种态度蛮无语的)。于是又看着拿过来的代码,进行了修改和扩展。
① 数组中的every方法
if (!Array.prototype.every) {
Array.prototype.every = function (every_fun, thisArg) {
var _this = null,
iKey = 0,
len = this.length; //无符号右移
if (typeof every_fun !== "function") {
throw new TypeError("every_fun is not a function");
}
if (thisArg) {
_this = thisArg;
}//绑定执行环境
for (; iKey < len; iKey++) {
var key_Value = this[iKey];
if(!every_fun.call(_this, key_Value, iKey, this)){
return false;
};
}
return true;
}
}
var arr = [2,33,22],
every_bool = arr.every(function(item,index,array){
return item >1;
});
alert(every_bool); //true
②数组的filter方法
if (!Array.prototype.filter) {
Array.prototype.filter = function (filter_fun, thisArg) {
var _this = null;
arr_fil = [],
iKey = 0,
arr_len = this.length;
if (typeof filter_fun != 'function') {
throw new Error('filter_fun is not a function');
}
if (thisArg) {
_this = thisArg;
}
for (; iKey < arr_len; iKey++) {
var key_value = this[iKey];
filter_fun.call(_this, key_value, iKey, this) && arr_fil.push(key_value);
}
return arr_fil;
}
}
var arr = [1, 23, 8]
filter_arr = arr.filter(function (item, index, array) {
return item > 2;
});
alert(filter_arr)//[23,8]
③ 数组的some 方法
if (!Array.prototype.some) {
Array.prototype.some = function (some_fun, thisArg) {
var _this = null,
iKey = 0,
arr_len = this.length;
if (typeof some_fun != 'function') {
throw new typeError('some_fun is not a function')
}
if (thisArg) {
_this = thisArg;
}
for (; iKey < arr_len; iKey++) {
var key_value = this[iKey];
// some_fun.call(_this, arr_value, i, this)&&return true;
if (some_fun.call(_this, key_value, iKey, this)) {
return true;
}
}
return false;
}
}
var arr = [0, 22, 33];
some_bool = arr.some(function (item, index, array) {
return item > 1;
})
alert(some_bool) //ture
至于其他的两种数组迭代的方法,大家照着写就好了,也蛮简单的。
在这里抛出一个问题,为什么逻辑与&&和逻辑或||操作符后面跟上return 会直接报错,有知道的小伙伴么,求大佬指导。