0

So basically, I made an empty array with JS, which is filled in dynamically based on user choice. Now, I would like a button to appear based on weather or not a value is stored inside the array. And I can't seem to do that, even though a required value is inside the array. Both array and button creation are the part of the same script, if such information makes difference. My code is something like this:

array = [];
//somewhere along the way it get's filled up...
//...
if (array.indexOf("anItem") == true){
var btn = document.createElement('button');
btn.innerHTML = "Text";
btn.setAttribute('id', 'button2');
paragra.appendChild(btn);
}

What am I doing wrong and is there hope for me?

1

2 Answers 2

3

Change the line from

if (array.indexOf("anItem") == true){

to

if (array.indexOf("anItem") != -1){

and let us know if there are any other problems. indexOf() returns the position of your value within the array, or -1 if it can't find it.

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

1 Comment

I tested it only a bit, but it seems to fix my issue. It didn't occur to me that the return value of indexOf is it not true/false. I will test it further later on. Thank you for your help!
1

This will work :-

array = [];

if(array.indexOf("anItem") != -1){
  //Item available
}else{
  // Item not available
}

indexOf returns the index of an Item in an array and if the Item is not found, it returns -1. The above code checks whether the indexOf("anItem") returns -1 or not.

Edit

BTW, a method named includes() is a part of ECMAScript 7. See this. However, ECMAScript 7 lacks browser support.

1 Comment

Thank you for you comment, it was very helpful. I will check out includes() method you mentioned, despite it's inflexibility.

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.