1

Im trying to check an array for a value as such. not sure how to go about. If anyone could help that would be great.

var array1 = [0]; if (DONT KNOW WHAT TO SAY TO CHECK FOR 0 IN THE ARRAY) { Do something } 
2
  • It depends on structure of your array! Commented Apr 16, 2016 at 11:56
  • You need to tell us what would be sample structures of the array in your context. Commented Apr 16, 2016 at 11:58

5 Answers 5

0

simple like this

if (array1[0] == "0") { //Do something } 

and if you have more values in your array you should use indexOf()

var array1 = [0, 3, 1, 4]; if (array1.indexOf(0) != -1) { //Do something } 
Sign up to request clarification or add additional context in comments.

Comments

0

DONT KNOW WHAT TO SAY TO CHECK FOR 0 IN THE ARRAY

If you want to check for 0 in the array1 (anywhere in the array), then use indexOf

if (array1.indexOf(0) != -1) { Do something } 

3 Comments

whats the difference between indexOf and contains?
@HenderikusParekowhai Array doesn't have built-in contains method developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@HenderikusParekowhai Also contains may mean that you are looking for value which has 0 as substring.
0
if(array1.indexOf(0) == 0){ //Do your code } 

Comments

0

Also you can do

for(var i in array){ if(array[i] == 0){ //Do all the things } } 

Comments

0

You need to access the array. If you have no idea what place the array is you need to go through the array.

for (var i = 0; i < array.length; i++) { if (array[i] == 0) { //Do all the things } } 

1 Comment

forgot all about indexOf. this is very inefficient so I would say go with those!! :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.