【发布时间】: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