代码之家  ›  专栏  ›  技术社区  ›  Marnes

为什么array.prototype.includes.bind会出现意外行为?

  •  0
  • Marnes  · 技术社区  · 5 年前

    鉴于现有的关于 function.bind 以及以下控制代码:

    console.log( [1, 2, 3].includes(2) ) // --> `true` 
    console.log( [null].map(String.prototype.toUpperCase, "abc") ) // --> `["ABC"]`  
    console.log( Array.prototype.includes.bind([3, 4, 5])(1) ) //--> `false`  
    console.log( Array.prototype.includes.bind([3, 4, 5])(4) ) // -- > `true`

    _ 是一个通用的实用程序包装器/polyfill

    [1, 2, 3].some(_.prototype.includes.bind(_([3, 4, 5]))) // --> `true`
    

    但是,为什么这段代码会产生这种意外的结果呢?

    console.log(
      [1,2,3].some(Array.prototype.includes.bind([3,4,5])) // --> `false`
    )

    编辑:我知道这段代码的字面形式不好,但这是一个poc,实际实现会有所不同(并且不能使用箭头函数,谢谢ie)

    2 回复  |  直到 5 年前
        1
  •  3
  •   adiga    5 年前

    这是 includes :

    arr.includes(valueToFind, [fromIndex])
    

    有一个可选的第二个参数 fromIndex .

    弗罗明德 :此数组中开始搜索valuetofind的位置

    所以,你的代码变成这样:

    [1,2,3].some((a,index) => Array.prototype.includes.bind([3,4,5])(a, index))
    // OR
    [1,2,3].some((a, index) => [3,4,5].includes(a, index))
    

    它在寻找 3 index = 2 .

    所以,如果你这样改变它,它会回来的 true

    console.log(
      // looks for from index=0
      [3,2,1].some(Array.prototype.includes.bind([5,4,3]))
    )
        2
  •  2
  •   Grillparzer    5 年前

    您可能没有想到的是.some()使用三个参数调用绑定函数,而不仅仅是包含该值的参数。

    你可以查一下 [1,2,3].some(console.log)

    includes接受两个参数,一个用于值,另一个用于偏移起始位置的可选参数。

    解决办法是:

    [3,2,1].some(n => Array.prototype.includes.bind([5,4,3])(n))