美文网首页JavaScript
[JavaScript] [].some(x=>fn(x)

[JavaScript] [].some(x=>fn(x)

作者: 何幻 | 来源:发表于2016-12-21 21:55 被阅读21次

    1. 问题描述

    以下函数为了判断两个集合是否有交集,可是r1r2的值居然是不同的。

    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])
    1. 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.
    2. thisArg: Optional. Value to use as this when executing callback.
    arr.includes(searchElement[, fromIndex])
    1. searchElement: The element to search for.
    2. 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]
    

    参考

    Array.prototype.some()
    Array.prototype.includes()

    相关文章

      网友评论

        本文标题:[JavaScript] [].some(x=>fn(x)

        本文链接:https://www.haomeiwen.com/subject/nkqcvttx.html