Home > Blockchain >  find specific number in array for if statement
find specific number in array for if statement

Time:03-26

I know there are alot of questions like this on here but they keep pointing me to using includes and that is not working for me for some reason.

Goal - use an if statement to find out if a number exists in an array. (Don't care if its jQuery or plan JS)

I tried using includes but that failed:

testdata = [1,256]
testdata.includes(1) #or testdata.includes(256)
\\false

enter image description here

I also tried using indexof but that failed too:

testdata = [1,256]
testdata.indexOf('256') >= 0
\\false

enter image description here

CodePudding user response:

Indeed, it looks like your array [1,256] is the first element of testdata array. In fact, you can see that testdata length is 1.

You should check if testdata[0].includes(1)

CodePudding user response:

Your array is numbers but your .indexOf argument is a string.

The snippet below works fine.

testdata = [1,256]
console.log(testdata.indexOf(256));

CodePudding user response:

It is not working for you because you use it in the wrong way. # is the private identifier in JS. If you use // instead it works.

testdata = [1,256];

testdata.includes(1) // or testdata.includes(256)

  • Related