Array对象的方法实现(5)----Array.prototype.includes(实现常规参数的功能)

10,Array的includes方法

includes() 方法用来判断一个数组是否包含一个指定的值,如果是,酌情返回 true或 false。
语法:arr.includes(searchElement) 或 arr.includes(searchElement, fromIndex)
注意:1,返回值为true(找到指定值),false(未找到指定值)。2,不改变原数组

Array.prototype._includes = function(searchElement,fromIndex){
	if (this === null) {
        throw new TypeError('"this" is null or not defined');
    }
	let that = Object(this),len = that.length >>> 0,param = arguments,index = fromIndex | 0;
	
	if(len === 0){return false;}
	
	startIndex = Math.max(index >= 0 ? index : len - Math.abs(index), 0);
	
	while(startIndex < len){
		if(String(that[startIndex]) === String(param[0]))return true;
		startIndex++
	}
	return false;
}


注意:

(1,通过startIndex获取开始查找的位置,如果开始位置大于length,返回false

(2,将that[startIndex]和param[0]转化为字符串比较的原因是我发现官方给的

console.log([1, 2, NaN].includes(NaN)); // true

我们都知道NaN === NaN会返回false,也就是说如果我们直接进行比较,会发现[1, 2, NaN]._includes(NaN)返回的是false,所以我在此处做了一个字符串转换处理。

测试:

var arr = ['a', 'b', 'c'];

console.log(arr.includes('a', -100)); // true
console.log(arr.includes('b', -100)); // true
console.log(arr.includes('c', -100)); // true

console.log(arr._includes('a', -100)); // true
console.log(arr._includes('b', -100)); // true
console.log(arr._includes('c', -100)); // true

console.log(arr.includes('c', 3));   //false
console.log(arr.includes('c', 100)); // false

console.log(arr._includes('c', 3));   //false
console.log(arr._includes('c', 100)); // false

console.log('_includes:'+[1, 2, 3]._includes(2));     // true
console.log([1, 2, 3]._includes(4));     // false
console.log([1, 2, 3]._includes(3, 3));  // false
console.log([1, 2, 3]._includes(3, -1)); // true
console.log('_includes:'+[1, 2, NaN]._includes(NaN)); // true
console.log('_includes:'+[1, 2, +0]._includes(-0));//true
console.log('_includes:'+[1, 2, -0]._includes(+0));//true


这样修改后示例测试基本都是对的,请问大神这个位置的NaN进行比较时,返回的是true,浏览器是怎么处理这个问题?

其他

[我的博客,欢迎交流!](http://rattenking.gitee.io/stone/index.html)

[我的CSDN博客,欢迎交流!](https://blog.csdn.net/m0_38082783)

[微信小程序专栏](https://blog.csdn.net/column/details/18335.html)

[前端笔记专栏](https://blog.csdn.net/column/details/18321.html)

[微信小程序实现部分高德地图功能的DEMO下载](http://download.csdn.net/download/m0_38082783/10244082)

[微信小程序实现MUI的部分效果的DEMO下载](http://download.csdn.net/download/m0_38082783/10196944)

[微信小程序实现MUI的GIT项目地址](https://github.com/Rattenking/WXTUI-DEMO)

[微信小程序实例列表](http://blog.csdn.net/m0_38082783/article/details/78853722)

[前端笔记列表](http://blog.csdn.net/m0_38082783/article/details/79208205)

[游戏列表](http://blog.csdn.net/m0_38082783/article/details/79035621)

原文地址:https://www.cnblogs.com/linewman/p/9918548.html