0
<!DOCTYPE HTML>
<html>

<body>

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

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

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

</body>

</html>

When I run the above code, it outputs "false", which isn't correct. If I change [[25,4]].includes([25,4]) to ['a'].includes('a'), it outputs the correct answer "true". Why does it do that?

pxc3110
  • 51
  • 3
  • 5
  • 1
    `includes` tests for strict equality meaning the two arrays would need to be the same array not two arrays that happen to hold the same values. It doesn't work for the same reason `[[25,5]] === [[25,5]]` is false. – Mark Sep 25 '18 at 00:07
  • `var tuple = [25, 24]; alert([tuple].includes(tuple))` there you go – Patrick Roberts Sep 25 '18 at 00:12

1 Answers1

2

That's because [25,4] !== [25,4] as the two operands refer to 2 different array objects. JavaScript do no consider 2 different objects equal. ['a'].includes('a') returns true as 'a' is a string (primitive value.) If you convert the 'a' into a String object the .includes method should return false. (Check 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

The .includes method should return true if you change your code into:

const item = [25,4];
const array = [item];
console.log(array.includes(item)); // true
Ram
  • 143,282
  • 16
  • 168
  • 197
  • But I have an array of lots of smaller arrays. So, what should I do to tell if a smaller array is this large array of arrays if I can't assign names to them one by one? – pxc3110 Sep 25 '18 at 00:40
  • @ZhiweiLiu Check this question: [javascript search array of arrays](https://stackoverflow.com/questions/6315180/javascript-search-array-of-arrays) – Ram Sep 25 '18 at 00:48
  • And I've found a duplicate question: https://stackoverflow.com/questions/19543514/check-whether-an-array-exists-in-an-array-of-arrays – Ram Sep 25 '18 at 00:51
  • What is the way to check that a `String` object say `a:string` with value `abc` contains `a`? – Manu Chadha Nov 21 '20 at 22:42