【问题标题】:Checking value of other array inside a map检查地图内其他数组的值
【发布时间】:2021-06-17 00:03:28
【问题描述】:

在这里,我有一张地图,我尝试检查 y 数组中 x 的值,如果找到则返回 true ,如果未找到预期输出 [true,false,true,false,false] 则返回 false 。根据我对x[2]y[2] 索引的了解,它应该进入if(x[index]===y[j]){ condition = true} 并返回true,但我得到的是[true,false,false,false,false]

const x = [1, 2, 3, 4, 5]
const y = [90, 80, 3, 6, 1]


const result = x.map((i, index) => {

  for (let j = 0; j < y.length; j++) {
    console.log(x[index], y[j])
    if (x[index] === y[j]) {
      condition = true
    } else {
      condition = false
    }
  }

  return (condition)
})


console.log(result)

【问题讨论】:

  • 你不会在找到任何匹配项后停止循环,所以你总是得到最后一个结果。整个for 循环就相当于x[index] === y[y.length - 1]
  • 当我 console.log(x[index], y[j])它显示了数组的所有值
  • 我可以很容易地证明这一点——循环不会停止。因此,只有最后一次迭代对condition 的值很重要。最后一次迭代将有j 等于y.length - 1。因此,唯一需要考虑的检查是 x[index] === y[y.length - 1],因为 index 是一个不变量。
  • 感谢您的回复,但我仍然没有得到它,可能我理解下一个循环是错误的。那么上述问题的正确解决方案是什么
  • Add more logging to see it better。您还可以使用调试器遍历代码。解决方案是在找到匹配项时停止循环。 Compare the output

标签: javascript arrays conditional-statements nested-loops array.prototype.map


【解决方案1】:

一种可能的解决方案是:

const x = [1, 2, 3, 4, 5]
const y = [90, 80, 3, 6, 1]


const result1 = x.map(el => y.includes(el))


console.log({result1})

// A more efficient one leverages the fast lookup of the `Set` data structure:

const ySet = new Set(y);
result2 = x.map(el => ySet.has(el))

console.log({result2})

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 2016-07-24
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多