weird output of the combination of $.each and jQuery.inArray function

297 Views Asked by At

My complete code:

jQuery.extend({

combinationCheck: function (p1position) {

    var Combination = [1, 2, 3, 4, 5, 6, 7, 8];
    Combination[0] = [1, 2, 3];
    Combination[1] = [4, 5, 6];
    Combination[2] = [7, 8, 9];
    Combination[3] = [1, 4, 7];
    Combination[4] = [2, 5, 8];
    Combination[5] = [4, 6, 8];
    Combination[6] = [1, 5, 9];
    Combination[7] = [3, 5, 7];


    $.each(p1position, function (index, value) {

        var num = value;

        if ($.inArray(String(value), Combination[1]) != '-1') {
            alert("there");
        }
        else {
            alert("not there");
        }

    });
});

so it works. If I were to set num to 5, it alerts "is there", and for 8 --> "not there". but the problem is I have another array.

p1position = [1,5];

and go through the array..

$.each(p1position,function(index,value){
    var num = value;
//then call the jQuery.inArray function as written above, it always return not there. even though 5 is in the Combination[1] array.
});

I am so confused of trying to solve this problem for hours.

1

There are 1 best solutions below

2
On

The specific problem with your code that you're asking about is that you're turning the value into a string before the check:

if ($.inArray(String(value), Combination[1]) != '-1') {
//            ^^^^^^^^^^^^^

inArray does an === (strict equality) check, and "1" !== 1. That line should read:

if ($.inArray(value, Combination[1]) !== -1) {

Changes:

  1. Don't turn the value into a string.

  2. Compare the result with -1 (a number), not "-1" (a string). inArray returns a number.

  3. Use !== rather than != (this is mostly a matter of style, you can use != if you prefer).


There are several other problems with that code, though.

  1. You're missing a }, so the code you say is your complete code doesn't parse.

  2. You're re-creating Combination every time the combinationCheck is called. If your goal is to create a Tic-Tac-Toe game, you're going to need to be able to retain the Combination state between checks.

Here's a fairly minimal set of fixes:

(function() {
    var Combination = [
            [1, 2, 3],
            [4, 5, 6],
            [7, 8, 9],
            [1, 4, 7],
            [2, 5, 8],
            [4, 6, 8],
            [1, 5, 9],
            [3, 5, 7]
        ];

    jQuery.extend({

        combinationCheck: function (p1position) {

            $.each(p1position, function (index, value) {

                if ($.inArray(value, Combination[1]) !== -1) {
                    alert(value + " is there");
                }
                else {
                    alert(value + " is NOT there");
                }

            });
        }
    });

})();

...which given:

jQuery.combinationCheck([1, 5]);

...reports that 1 is not found, but 5 is.

Live copy