学无先后,达者为师

网站首页 编程语言 正文

Array.prototype.myfindIndex

作者:web半晨 更新时间: 2022-06-06 编程语言


1、概念

findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引(下标)。若没有找到对应元素则返回-1。


2、MDN链接地址

MDN - findIndex


3、示例代码

let arrayData = [4, 6, 8, 12];

Array.prototype.myfindIndex = function(callback, context) {
	// 获取第二个参数,
	// 即this指向。
	// 如果有直接使用,
	// 否则,指向window
	context = context || window;

	// 获取this的长度。
	let len = this.length;

	// 初始化while的值。
	let i = 0;

	while (i < len) {
		// 调用函数
		if (callback.call(context, this[i], i, this)) return i;

		i++;
	};

	return -1;
};

let fun = function(item) { 
	return item + this.svalue > 10;
};

console.log(arrayData.myfindIndex(fun, { svalue: 5 }));
// 1

原文链接:https://blog.csdn.net/weixin_51157081/article/details/115794916

栏目分类
最近更新