ES6的新语法用ES5的写法

在做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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值