1. 问题描述
以下函数为了判断两个集合是否有交集,可是r1
和r2
的值居然是不同的。
hasIntersection = (smallSet, bigSet) => {
let fn = bigSet.includes.bind(bigSet);
let r1 = smallSet.some(fn); //false
let r2 = smallSet.some(ele => fn(ele)); //true
console.log(r1, r2);
}
hasIntersection([1, 2], [2, 3]);
2. [].some与[].includes
arr.some(callback[, thisArg])
- callback: Function to test for each element, taking three arguments:
(1) currentValue: The current element being processed in the array.
(2) index: The index of the current element being processed in the array.
(3) array: The array some() was called upon. - thisArg: Optional. Value to use as this when executing callback.
arr.includes(searchElement[, fromIndex])
- searchElement: The element to search for.
- fromIndex: Optional. The position in this array at which to begin searching for searchElement. A negative value searches from the index of array.length + fromIndex by asc. Defaults to 0.
3. 结论
所以,smallSet.some(fn)
并不等价于smallSet.some(ele=>fn(ele))
,
而是等价于:smallSet.some((...args)=>fn(...args))
,
即,smallSet.some((currentValue,index,array)=>fn(currentValue,index,array))
这样index
,就变成了includes
的第二个参数fromIndex
了。
4. 另外一个例子
["10", "10", "10", "10"].map(parseInt)
> [10, NaN, 2, 3]
["10", "10", "10", "10"].map(x=>parseInt(x))
> [10, 10, 10, 10]
网友评论