0

I'm running a 'for' loop to check if the elements in the winOptions array are in the oneNums array. However, every time I use indexOf property it sends back -1 even if the number is in the oneNums array. Is it possible it returns that because ['1','2'] is different that [1,2]? How can I fix this.

I have this variables:

 var oneNums = []; var winOptions = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[3,5,9],[1,4,7],[2,5,8],[3,6,9]]; var a; 

And this jQuery function:

$('.btn-xo').click(function(){ if (turn === 'one'){ $(this).text(pickOne); $(this).prop('disabled', true); oneNums.push($(this).val()); oneNums.sort(function(a, b){ return a - b; }); for(var i = 0; i < winOptions.length; i++){ for(var j = 0; j < winOptions[i].length; j++){ a = oneNums.indexOf(winOptions[i][j]); if (a === -1){ p1 = []; break; } else { p1.push(oneNums[a]); console.log('aca'); } } } console.log(a); turn = 'two'; count += 1; } 
4
  • Can you add a snippet for this as your code has some missing vars Commented Mar 23, 2017 at 5:12
  • @Harsheet give me a sec. I'll do it. Commented Mar 23, 2017 at 5:13
  • 1
    oneNums.push(parseInt($(this).val(), 10)); can check parsing it? Commented Mar 23, 2017 at 5:14
  • Print oneNums array and check,whether it is having preferred values. Commented Mar 23, 2017 at 5:15

1 Answer 1

2

indexOf string with number will fail. So, change number to string

First convert number to String, using .toString()

for(var i = 0; i < winOptions.length; i++){ for(var j = 0; j < winOptions[i].length; j++){ a = oneNums.indexOf((winOptions[i][j]).toString()); if (a === -1){ p1 = []; break; } else { p1.push(oneNums[a]); console.log('aca'); } } } 

Check these two examples,

['1','2'].indexOf(1); o/p ===> -1

['1','2'].indexOf((1).toString()); o/p ===> 0

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

2 Comments

Exactly what I was asking for. So it is different the 1 and the '1'. Thanks!
@DiegoRios, yes your suspicion is correct, that's the culprit. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.