众所周之,IE8及以下的浏览器中方法较少,像Array原型中的indexof方法在IE8及以下的浏览器中会出现undefined;
那么我们如何做到兼容呢;方法如下:
if (!Array.prototype.indexOf) { //如果Array.prototype中不存在indexof方法,就执行下面代码 Array.prototype.indexOf = function (val, index) {//在Array原型中创建一个indexof方法 index = index === undefined ? 0 : index; //如果没传参数index,就让index为0 for (; index < this.length; index++) { if(this[index] === val){ return index; //返回数组下标值 } } return -1; //没在数组中找到,就返回-1 } } var arr = [1,2,3,45];
console.log(arr.indexOf(3)); // 2
console.log(arr.indexOf(10)); // -1