JavaScript数组操作——遍历方法的兼容
JavaScript数组操作——遍历方法的兼容 1.1概述 ECMA Script5中数组方法如indexOf()、forEach()、map()、filter()、some()不支持IE6~8。 1.2兼容写法 以下兼容性写法均可兼容至IE6。 1.2.1indexOf()方法兼容
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(ele) {
var len = this.length; //获取数组长度
var fromIndex = Number(arguments[1]) || 0; //检查值为数字的第二个参数是否存在,默认值为0
//当第二个参数小于0时,为倒序查找,相当于查找索引值为该索引加上数组长度后的值
if(fromIndex < 0) { fromIndex += len; }
//从fromIndex起循环数组
while(fromIndex < len) {
//检查fromIndex是否存在且对应的数组元素是否等于ele
if(fromIndex in this && this[fromindex] === ele) { return fromIndex; }
fromIndex++;
}
//当数组长度为0时返回不存在的信号:-1
if (len === 0) { return -1;}
}
}
1.2.2 forEach()方法兼容
if ( !Array.prototype.forEach) {
Array.prototype.forEach = function forEach(callback) {
var len = this.length;
if(typeof callback != "function") { throw new TypeError(); }
//thisArg为callback 函数的执行上下文环境
var thisArg = arguments[1];
for(var i = 0; i < len; i++) {
if(i in this) {
//callback函数接收三个参数:当前项的值、当前项的索引和数组本身
callback.call(thisArg, this[i], i, this);
}
}
}
}
1.2.3 map()方法兼容
if (!Array.prototype.map) {
Array.prototype.map = function(callback) {
var len = this.length;
if(typeof callback != "function") { throw new TypeError(); }
//创建跟原数组相同长度的新数组,用于承载经回调函数修改后的数组元素
var newArr = new Array(len);
var thisArg = arguments[1];
for(var i = 0; i < len; i++) {
if(i in this) { newArr[i] = callback.call(thisArg, this[i], i, this); }
}
return newArr;
}
}
1.2.4 filter()方法兼容
if (!Array.prototype.filter) {
Array.prototype.filter = function(callback) {
var len = this.length;
if(typeof callback != "function") { throw new TypeError(); }
//创建新数组,用于承载经回调函数修改后的数组元素
var newArr = new Array();
var thisArg = arguments[1];
for(var i = 0; i < len; i++) {
if(i in this) {
if(callback.call(thisArg, this[i], i, this)) { newArr.push(val); }
}
}
return newArr;
}
}
1.2.5 some()方法兼容
if (!Array.prototype.some) {
Array.prototype.some = function(callback) {
var len = this.length;
if(typeof callback != "function") { throw new TypeError(); }
var thisArg = arguments[1];
for(var i = 0; i < len; i++) {
if(i in this && callback.call(thisArg, this[i], i, this)) { return true; }
}
return false;
}
}
1.2.6 every()方法兼容
if (!Array.prototype.every) {
Array.prototype.every = function(callback) {
var len = this.length;
if(typeof callback != "function") { throw new TypeError(); }
var thisArg = arguments[1];
for(var i = 0; i < len; i++) {
if(i in this && !callback.call(thisArg, this[i], i, this)) { return false; }
}
return true;
}
}