在做IE浏览器兼容时,由于IE浏览器不支持一些ES6的写法,所以讲ES6的一些方法使用ES5写法来写
find
Array.prototype.find || (Array.prototype.find = function(predicate) {
if(this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if(typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length || 0;
var thisArg = arguments[1];
var value;
for(var i = 0; i < length; i++) {
value = list[i];
if(predicate.call(thisArg, value, i, list)) {
return value;
}
}
return null;
})
findIndex
if(!Array.prototype.findIndex) {
Object.defineProperty(Array.prototype, 'findIndex', {
value: function(predicate) {
// 1. Let O be ? ToObject(this value).
if(this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if(typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while(k < len) {
var kValue = o[k];
if(predicate.call(thisArg, kValue, k, o)) {
return k;
}
k++;
}
return -1;
}
});
}
indexOf
if (!Array.indexOf) {
Array.prototype.indexOf = function (obj) {
for(var i = 0;i < this.length;i++){
if (this[i] == obj) {
return i;
}
}
return -1;
}
}