Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use Array#includes for a nested array?

Why does the following line return false in Javascript:

 [[1,2,3], [1,2,4]].includes([1,2,3]);

What is the underlying logic behind that?

like image 796
katus Avatar asked Jan 04 '18 04:01

katus


People also ask

Why Cannot arrays be passed by values to functions?

Arrays are not passed by value because arrays are essentially continuous blocks of memmory. If you had an array you wanted to pass by value, you could declare it within a structure and then access it through the structure.

Why can't I print an array in Java?

You cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional array.

Can't change an array in Excel?

You click the formula in the cell or formula bar and you can't change a thing. Array formulas are a special case, so do one of the following: If you've entered a single-cell array formula, select the cell, press F2, make your changes, and then press Ctrl+Shift+Enter..


1 Answers

includes compares using SameValueZero equality algorithm. (As mentioned in developer.mozilla.org). When searching for objects (array is object as well), it will match only references to the same object.

Additionally, Javascript arrays are objects and you can't simply use the equality operator == to understand if the content of those objects is the same. The equality operator will only test if two object are actually exactly the same instance (e.g. myObjVariable==myObjVariable, works for null and undefined too).

like image 94
Duc Filan Avatar answered Sep 26 '22 00:09

Duc Filan