【问题标题】:Javascript includes() in list of list not working [duplicate]列表列表中的Javascript包含()不起作用[重复]
【发布时间】:2021-04-22 05:58:25
【问题描述】:
var coords = [
    [0,0],[5,0],[0,5],[5,5],[8,5],[8,0],[40,5],[5,54],[6,7],[40,0],[8,54]
]
console.log(coords.includes([0,0]))

这里的结果是假的,我不确定为什么。请帮忙

【问题讨论】:

标签: javascript arrays


【解决方案1】:

Array.prototype.includes 使用严格相等运算符比较值。数组是按引用而不是按值存储的。 [] === [] 永远不会是真的,除非你比较存储在你的数组中的同一个数组。

解决此问题的一种方法是使用Array.prototype.some

var coords = [
    [0,0],[5,0],[0,5],[5,5],[8,5],[8,0],[40,5],[5,54],[6,7],[40,0],[8,54]
]
console.log(coords.some(coordinate => {
const [x, y] = coordinate
// This is the value you are comparing
const myCoords = [0, 0]
return x === myCoords[0] && y === myCoords[1]
}))

【讨论】:

  • 非常感谢。
猜你喜欢
  • 2016-05-31
  • 1970-01-01
  • 2018-05-13
  • 2014-06-10
  • 1970-01-01
  • 2016-12-13
  • 2018-04-15
  • 2020-08-02
  • 1970-01-01
相关资源
最近更新 更多