2

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.

2
  • 3
    [0, 2].includes(2) === true here. You'll need to provide more code to demonstrate your issue. Commented Feb 22, 2018 at 16:20
  • You have to show us where you initialise array_type and where you use it Commented Feb 22, 2018 at 16:23

6 Answers 6

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

@AdamŠulc Glad I helped :)
2

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

2 Comments

I did not know that I have to put [0,1] in there. Is there any way that it woud work without it? Because not everytime the array will contain only two items.
yes of course you can use functions of array like push / unshift to provide values to the array. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
2

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.

Comments

2

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");
}

Comments

1
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!

Comments

1

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

Because using first option, it works:

> array_type.includes(2)
true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.