forEach和map的兼容性写法

一、map和forEach的用法

            var arr2 = [2,4,6,8]
			// item:数组每一项
			// index:下标
			// arr:遍历的数组
			arr2.forEach(function(item,index,arr) {
				console.log('item', item) // 2,4,6,8
			})
			var arr3 = arr2.map(function(item,index,arr) {
				return item*2
			})
			console.log(arr3) // [4,8,12,16]

因为map和forEach方法在IE9以下都是不支持的,要在ie9以下兼容map和forEach,需要做特殊处理

二、IE9以下的兼容写法

            /**forEach方法*/
			// 两个参数和forEach里面方法是一样的
			// callback:回调函数
			// context [object] 上下文;
			// this:遍历的数组
			// this[i]:数组的每一项
			// i:index
			Array.prototype.myForEach = function myForEach(callback, context) {
				context = context || window;
				if(Array.prototype.forEach) {
					// 调用forEach方法,不做任何处理
					this.forEach(callback, context);
					console.log('支持forEach方法')
					return;
				}
				//IE6-8下自己编写回调函数执行的逻辑
				for(var i = 0, len = this.length; i < len; i++) {
					// for循环给callback回调传入相应的参数
					callback && callback.call(context, this[i], i, this);
				}
			}
			/**map方法*/
			Array.prototype.myMap = function myMap(callback, context) {
				context = context || window;
				if(Array.prototype.map) {
					console.log('支持map方法')
					return this.map(callback, context);
				}
				//IE6-8下自己编写回调函数执行的逻辑
				var newAry = [];
				console.log('要遍历的数组', this)// 遍历的数组
				console.log('回调函数', callback)//回调函数
				console.log('上下文', context)// 上下文
				for(var i = 0, len = this.length; i < len; i++) {
					console.log('要遍历的数组长度', this.length)//该数组的长度
					console.log('数组项', this[i])// 数组每一项
					if(typeof callback === 'function') {
						var val = callback.call(context, this[i], i, this);
						newAry[newAry.length] = val;
						console.log('处理后结果', val)// 处理后的结果
					}
				}
				return newAry;
			}

调用方法:myMap和myForEach

            var arr = [1, 2, 4, 6]
			arr.myForEach(function(item, index, arr) {
				console.log('forEach', item) // 1,2,4,6
			})
			var res = arr.myMap(function(item, index) {
				return item*2
			})
			console.log('结果', res)// [2,4,8,12]

数组优化的方法:

            var arr1 = [1, 2, 3, 4, 5, 6];
            for(var i = 0, len = arr1.length; i < len; i++) { //优化性能处理,不用每次循环都获取arr1.length
                console.log(arr1[i], 'for遍历出来的数据'); //每个item  1,2,3,4,5,6
            }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值