问题一:
这是一个乌龙问题。
function(){
console.log([].includes(NaN)); //true 实验结果
console.log([].includes(3)); //false 实验结果
}(1,2,4,5,NaN)
相当纳闷,参数是怎么传出去的。。。是否存在我还不知道的潜规则??
as we know
function 有一个属性——arguments:包含所有传进方法的参数
一开始我想源码里是不是这样写了
Array.prototype.includes = function(){
//value:调用此方法对象
var value = this || !function(){
var tempArr = []
for(var i =0;i<arguments.length,i++){
tempArr.push(arguments[i]);
}
return tempArr
}()
...
}
本着格物致知的原则,确定一下,没找到源码。
回顾看了一下
https://developer.mozilla.org/
示例代码
(function() {
console.log([].includes.call(arguments, 'a')); // true
console.log([].includes.call(arguments, 'd')); // false
})('a','b','c');
原来用了call
那么问题又来了
includes()源码到底怎么写的。
伪代码如下
Let O be ? ToObject(this value).
Let len be ? ToLength(? Get(O, "length")).
If len is 0, return false.
Let n be ? ToInteger(fromIndex). (If fromIndex is undefined, this step produces the value 0.)
If n ≥ 0, then
Let k be n.
Else n < 0,
Let k be len + n.
If k < 0, let k be 0.
Repeat, while k < len
Let elementK be the result of ? Get(O, ! ToString(k)).
If SameValueZero(searchElement, elementK) is true, return true.
Increase k by 1.
Return false.
查询一下SameValueZero
是Es6的方法
SameValueZero: used by %TypedArray% and ArrayBuffer constructors, as well as Map and Set operations, and also String.prototype.includes and Array.prototype.includes since ES2016
what’s it?
http://www.ecma-international.org/ecma-262/7.0/
The internal comparison abstract operation SameValueZero(x, y), where x and y are ECMAScript language values, produces true or false. Such a comparison is performed as follows:
If Type(x) is different from Type(y), return false.
If Type(x) is Number, then
If x is NaN and y is NaN, return true.
If x is +0 and y is -0, return true.
If x is -0 and y is +0, return true.
If x is the same Number value as y, return true.
Return false.
Return SameValueNonNumber(x, y).
NOTE [笔记]
SameValueZero differs from SameValue only in its treatment of +0 and -0.
欧克
这就可以解决了——为什么includes() 可以判断NaN是否在数组里
REMAKE [备注]
→7.2.11SameValueNonNumber (x, y)
The internal comparison abstract operation SameValueNonNumber(x, y), where neither x nor y are Number values, produces true or false. Such a comparison is performed as follows:
Assert: Type(x) is not Number.
Assert: Type(x) is the same as Type(y).
If Type(x) is Undefined, return true.
If Type(x) is Null, return true.
If Type(x) is String, then
If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true; otherwise, return false.
If Type(x) is Boolean, then
If x and y are both true or both false, return true; otherwise, return false.
If Type(x) is Symbol, then
If x and y are both the same Symbol value, return true; otherwise, return false.
Return true if x and y are the same Object value. Otherwise, return false.
人不装B伪少年,by h.k
2017年12月29日
看源码是爱好、解决问题是职业——h.k