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;
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.