【问题标题】:JavaScript doesn't detect indexOf -1 in array [duplicate]JavaScript 未检测到数组中的 indexOf -1 [重复]
【发布时间】:2018-01-05 00:40:47
【问题描述】:

我有一个简单的脚本,它使一个夹具匹配一个数组的所有值。

const players = ['a', 'b', 'c', 'd'];
const matches = [];

players.forEach(k => {
  players.forEach(j => {
    if(k !== j) {
      let z = [k, j]
      z.sort()
      const inArray = matches.indexOf(z) !== -1

      if(!inArray) matches.push(z)

      console.log(matches)
    }

  })
})

虽然询问 Javascript 搜索 z 是否在 matches 数组中,但结果有重复项并返回:

[ 'a', 'b' ]​​​​​​

​​​​​[ 'a', 'c' ]​​​​​​

​​​​​[ 'a', 'd' ]​​​​​​

​​​​​[ 'a', 'b' ]​​​​​​ --> duplicated item

​​​​​[ 'b', 'c' ]​​​​​​

​​​​​[ 'b', 'd' ]​​​​​​

​​​​​[ 'a', 'c' ]​​​​​​ --> duplicated item

​​​​​[ 'b', 'c' ]​​​​​​ --> duplicated item

​​​​​[ 'c', 'd' ]​​​​​​

​​​​​[ 'a', 'd' ]​​​​​​ --> duplicated item

​​​​​[ 'b', 'd' ]​​​​​​ --> duplicated item

​​​​​[ 'c', 'd' ]​​​​​​ --> duplicated item

如何避免这些重复项?

【问题讨论】:

  • indexOf() 不带数组。
  • indexOf 寻找相等性,因此只有原语才能真正像那样工作。即:"a" === "a" // true,但[] === [] // false。试试看this question
  • 你为什么打电话给z.sort()
  • 它们不是重复的。这是因为您正在对它们进行排序(例如,您的第二个 ['a', 'b'] 实际上是 ['b', 'a']
  • 首先不生成这些重复项的解决方案怎么样? players.forEach((v,i,a) => { while(++i < a.length) matches.push([v, a[i]]) })Array.from(new Set(players)).forEach(...) 如果玩家本身可能包含重复项。

标签: javascript arrays algorithm indexof


【解决方案1】:

我假设您的意思是if(!inArray) matches.push(z),对吧?无论哪种方式,indexOf 都不会比较数组的 ,而是实际上检查引用等价,即 数组实例本身是否相等

为了正确比较数组的,您可能需要编写一个辅助函数来代替indexOfLuckily, this answer explains how to do just that.

Additionally, here is a great article on MDN which breaks down various kinds of equality comparisons.

【讨论】:

    【解决方案2】:

    如果数组项始终是字符串,你可以做一些小技巧,但会完成工作

    const players = ['a', 'b', 'c', 'd'];
    const matches = [];
    
    players.forEach(k => {
      players.forEach(j => {
        if(k !== j) {
          let z = [k, j];
    
          z.sort()
          const inArray = matches.map(match=>match.join('')).indexOf(z.join('')) !== -1
    
          if(!inArray) matches.push(z)
    
          console.log(matches)
        }
    
      })
    })
    

    基本上,您在比较之前将数组转换为字符串,这为 javascript 提供了一种检查它们是否相等的方法。检查数组实例之间的相等性不起作用,并且会返回不需要的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      相关资源
      最近更新 更多