【问题标题】:javascript includes method outputs incorrect result [duplicate]javascript包含方法输出不正确的结果[重复]
【发布时间】:2019-02-28 12:38:17
【问题描述】:
<!DOCTYPE HTML>
<html>

<body>

  <p>Before the script...</p>

  <script>
    alert([[25,4]].includes([25,4]));
  </script>

  <p>...After the script.</p>

</body>

</html>

当我运行上面的代码时,它输出“false”,这是不正确的。如果我将 [[25,4]].includes([25,4]) 更改为 ['a'].includes('a'),它会输出正确答案“true”。为什么这样做?

【问题讨论】:

  • includes 测试严格相等,这意味着两个数组需要是同一个数组,而不是恰好保存相同值的两个数组。由于 [[25,5]] === [[25,5]] 为假的相同原因,它不起作用。
  • var tuple = [25, 24]; alert([tuple].includes(tuple)) 你去吧

标签: javascript


【解决方案1】:

这是因为[25,4] !== [25,4] 作为两个操作数引用了两个不同的数组对象。 JavaScript 不认为 2 个不同的对象相等。 ['a'].includes('a') 返回 true,因为 'a' 是一个字符串(原始值)。如果将 'a' 转换为 String 对象,.includes 方法应该返回 false。 (查看What is the difference between JavaScript object and primitive types?

'a' === 'a' // true
new String('a') === new String('a') // false
[new String('a')].includes(new String('a')) // false

如果您将代码更改为,.includes 方法应返回 true

const item = [25,4];
const array = [item];
console.log(array.includes(item)); // true

【讨论】:

  • 但是我有很多较小的数组。那么,如果我不能一个一个地为它们分配名称,我应该怎么做才能判断一个较小的数组是否是这个大数组?
  • @ZhiweiLiu 检查这个问题:javascript search array of arrays
  • 我发现了一个重复的问题:stackoverflow.com/questions/19543514/…
  • 检查String 对象说a:string 的值abc 包含a 的方法是什么?
猜你喜欢
  • 2020-10-26
  • 2018-08-27
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 2021-04-12
  • 2017-11-09
相关资源
最近更新 更多