给Array扩展一个each方法

我们来写一个 each 方法,然后挂载到 Array 的 prototype 上
要实现的功能:

  1. 必传参数 callback,如果有异常则抛出异常
  2. 如果只有一个callback,则里面的 this 指向 window
  3. 如果有第二个参数 obj, 则把 this 执行第二个参数 obj
  4. 生成一个新的数组,用来返回处理过后的数据
function each (callback, obj) {
		let newArr = [];
		// 如果有异常,抛出
		try{ 
			if (callback === undefined) throw new Error("There should be a callback function in each method");
			if (callback !== undefined && typeof callback !== "function") throw new Error("Callback is not a function");
		}
		catch (err) {
			console.error(err);
			return false
		}
		
		// return value
		let flag;
		
		// judge function 
		function judge (bol, arrValue) {
			if (!bol) newArr.push(arrValue);
			else {
				newArr.push(bol);
			}
		}
		
		
		// 循环数组
		for (let i = 0; i < this.length; i++) {
		
			// Determine whether there is a second parameter
			if (obj === undefined) {
				flag = callback(arr[i], i);
				judge(flag,arr[i]);
			} else if (typeof obj === "object") {
				// 将 this 指向挂到 obj 上
				flag = callback.call(obj, arr[i], i);
				judge(flag,arr[i]);
			}
		}
		return newArr;
	}
	
	Array.prototype.each = each;
	
	// test
	let arr = [10, 20, 30, 'AA', 40];
	let obj = {};
	arr = arr.each(function(item, index){
		// obj
		this[index] = item;
		if (isNaN(item)) return false;
		return item * 10;
	},obj)
	console.log(arr);   // [100, 200, 300, 'AA', 400]
	console.log(obj);   // {0: 10, 1: 20, 2: 30, 3: "AA", 4: 40}

公众号:Coder 杂谈,欢迎关注
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值