0

This might be a duplicate but I could not help but post this, I have an array with this format

answerCollection= {
0:
{selected : a,
 status :  false   
 },
1:
{selected : a,
 status :  false   
 }
}

I want to do an index check on the this aray like this

if(answerCollection.indexOf(indexNo) == -1){
 sel = "a";
 }

but it keeps failing i.e. I keep getting a return value of -1, irrespectively of if the index exist in the array or not.

How do I do this kind of search?

11
  • 8
    That's an object, not an array. Commented Jun 4, 2013 at 14:18
  • Seems like answerCollection is a plain object instead of array. Also, the argument for indexOf is the value and not the key. Commented Jun 4, 2013 at 14:18
  • 1
    What happens if you do if (!answerCollection[indexNo]) { ... }? Commented Jun 4, 2013 at 14:19
  • I declared it like dis var answerCollection = []; Commented Jun 4, 2013 at 14:19
  • @Lloyd I passed it to a var to check, I keep getting -1 on it Commented Jun 4, 2013 at 14:20

2 Answers 2

2
if(indexNo in answerCollection){
 sel = "a";
 }

Best practice to detect properties in an object. In your case, maybe you need to convert to string

if(indexNo.toString() in answerCollection){
     sel = "a";
     }
Sign up to request clarification or add additional context in comments.

1 Comment

Probably right, but explain what it does (or link to docs) to avoid confusion!
0
if(answerCollection[indexNo] == null){
 sel = "a";
}

for example look here.

4 Comments

@Lloyd null coerces to undefined. undefined can be shadowed, null can't. null is shorter to type and in file size.
@FabrícioMatté Yes I forgot about that :)
Oh no problem. Since we're nitpicking, I'd go with if (!answerCollection[indexNo]) =]
:) I prefer my null, since I defined the collection.

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.