【问题标题】:Passing an array for includes() as first argument [duplicate]将包含()的数组作为第一个参数传递[重复]
【发布时间】:2022-08-18 17:32:13
【问题描述】:

代码示例:

let names = [
    [\'John\', 24],
];

names.includes([\'John\', 24]) // false

不应该记录在案吗?

  • 这是因为它们不是同一个数组。 [] === [] //false
  • 使用JSON.stringify() 匹配子字符串,JSON.stringify(names).includes(JSON.stringify([\'John\', 24])) // TRUE
  • 谢谢,想通了
  • \"不应该记录在案吗?\" 为什么你认为不是? 30 多年来,JS 一直在比较对象的身份。这是 JS 中的惯用语,.includes() 方法也不例外,它与 @987654327 对称@ 已经工作了很长时间了。身份比较既不是“不寻常的”,也不是无证的。

标签: javascript


【解决方案1】:

感谢@evolutionxbox,我发现底层的 JavaScript 会比较这些数组的严格相等性。

顺便说一句,这有效:

let person = ['John', 24];

let names = [
    person,
];

names.includes(person) // true

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 2015-08-21
    • 2015-09-14
    • 2014-06-22
    • 2013-07-24
    • 1970-01-01
    • 2017-12-02
    • 2013-08-13
    • 2021-03-22
    相关资源
    最近更新 更多