const myArray = [
[2, 4], "cat", "hamster", 9
]
console.log(myArray.includes("cat"))
console.log(myArray.includes([2, 4]))
output is true, false. does includes() not work for arrays inside of arrays? thanks
const myArray = [
[2, 4], "cat", "hamster", 9
]
console.log(myArray.includes("cat"))
console.log(myArray.includes([2, 4]))
output is true, false. does includes() not work for arrays inside of arrays? thanks
Because Array in js is a specific object, the [2,4] inside myArray is object and [2,4] that you switch to includes is anther object. If you want that includes return true you must do this:
var array = [2, 4]
const myArray = [array, "cat", "hamster", 9]
console.log(myArray.includes(array))
A string is a value type, so a comparison between two strings will compare the value of those strings. In your case the value cat
.
However, an array is an object with reference comparison, not value comparison. So when comparing two arrays the reference will be compared. That is if you compare the same object to itself the result will be true. However, as is the case in your example, if you compare two different objects even with all the properties set to the same value, the result will be false.
let a = [1,2];
let b = 2;
let c = "string";
let d = [1,2];
a === a; //true reference comparison comparing an object to itself
b === 2; //true value comparison
c === "string"; //true again value comparison, even though it's two different objects
a === d; //false the values are the same but it's reference comparison
Array.includes iterates through the array and makes a comparison between the argument and the individual elements using the above comparison types depending on the types.
It's also important to note that includes uses strict comparison. That is if a comparison with ===
results in true
then so would includes
. It's not enough that ==
would result in true. "2" == 2
is an example of a comparison that returns true where ["2"].includes(2)
returns false