【问题标题】:Why (thisIsInTheArray in array) returns false? [duplicate]为什么(数组中的thisIsInTheArray)返回false? [复制]
【发布时间】:2018-01-27 15:02:30
【问题描述】:
var codeList = [ "ok", "error" ]
var msg = { "status": "ok" }
console.log(msg.status in codeList) // returns false

它似乎可以在我的 iPad 上运行,但不能在我的电脑上运行。这是我的 Chrome 64.0.3282.119、Windows 10 x64、JavaScript V8 6.4.388.40 的屏幕截图:

【问题讨论】:

  • @Pointy 所以我可以使用{ ok: "", error: "" },然后使用in
  • in 运算符测试对象是否定义了属性。例如,"0" in codeList 将是 true
  • 谢谢大家,顺便说一句对不起重复。

标签: javascript arrays json


【解决方案1】:

根据documentation

如果指定的 property 在 指定对象或其原型链。

请改用array.includes()

PS:MDN documentation 中有很多有趣的东西;)

【讨论】:

  • 据我了解,他只需要检查状态是否是允许的状态之一,所以 codeList.includes(msg.status) 应该做的工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
  • 2021-11-10
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
相关资源
最近更新 更多