Adam Šulc
Adam Šulc

Reputation: 546

JS - array.includes issue

I have this issue with a JS function array.includes. I have this array:

The thing is when I use this code, nothing will happen.

var array_type;
//array has these 2 values:
//array_type[0] == 0;
//array_type[1] == 2;
if (array_type.includes(2)) {
 console.log("good");
}

Do you have any idea why? Thank you for any help.

Upvotes: 2

Views: 2483

Answers (6)

Sanchit Patiyal
Sanchit Patiyal

Reputation: 4920

If you are using Internet Explorer then array.includes() will not work. Instead you need to use indexOf. Internet Explorer doesn't have a support for Array.includes()

var array_type = [0, 2];

if (array_type.indexOf(2) !== -1) {
  console.log("good");
}

References for includes()

References for indexOf()

Check the browser compatibility sections in the link

Upvotes: 4

aconsuegra
aconsuegra

Reputation: 186

Here your are not adding values, you are testing if array_type[0] is equal to 0 and array_type[1] is equal to 2

//array has these 2 values:
array_type[0] == 0;
array_type[1] == 2;

So this code

if (array_type.includes(2)) {
    console.log("good");
}

never be true Try

var array_type = [];
array_type[0] = 0;
array_type[1] = 2;

if (array_type.includes(2)) {
    console.log("good");
}

Upvotes: 2

Ignacio Ara
Ignacio Ara

Reputation: 2582

I suppose that both comments is a value set (=) instead of a comparison (==)

Because using first option, it works:

> array_type.includes(2)
true

Upvotes: 1

L Y E S  -  C H I O U K H
L Y E S - C H I O U K H

Reputation: 5090

var array_type = [];
//array has these 2 values:
array_type[0] = 0;
array_type[1] = 2;
if (array_type.includes(2)) {
     console.log("good");
}

This should work!

Upvotes: 1

cbrawl
cbrawl

Reputation: 985

The code works for me. For example,

var array_type = [0, 2];

if (array_type.includes(2)) {
    console.log("good");
}

will log good.

Make sure you are properly inserting the items into the array.

Upvotes: 2

juan garcia
juan garcia

Reputation: 1526

This code works

[1,2].includes(2)

but you have to be careful if you can use the includes function

https://caniuse.com/#search=includes

Upvotes: 2

Related Questions