0

Hey everyone, I've been creating a little chat bot (for fun and practice).

I have the following function which isn't working correctly (FULL CODE HERE):

function runAI() {
            if (i.val().length > 0) { 
                if ($.inArray(i.val(), helloInputArray)) {
                    r = Math.floor(Math.random()*4);                        
                    o.html(o.html()+helloOutputArray[r]);
                    i.val('');
                    i.focus();
                } else if ($.inArray(i.val(), byeInputArray)) {
                    r = Math.floor(Math.random()*4);                        
                    o.html(o.html()+byeOutputArray[r]);
                    i.val('');
                    i.focus();
                } else {
                    o.html(o.html()+"I don't know what that means...<br />");
                    i.val('');
                    i.focus();
                }
            }
        }

It always seems to return the helloOutputArray...

Barrie Reader
  • 10,647
  • 11
  • 71
  • 139

1 Answers1

2

$.inArray does not return true or false, it returns a 0 based index.

-1 means not found, > -1 is the index of the match in the array:

if ($.inArray(i.val(), helloInputArray) > -1) {
    // The item was in this array
}

Working version here.

djdd87
  • 67,346
  • 27
  • 156
  • 195
  • 1
    @Neurofluxation - I actually already gave you an example of this in your last question:) http://stackoverflow.com/questions/3716477/is-there-a-way-where-i-can-hold-all-potential-arguments-in-an-array/3716495#3716495 – djdd87 Sep 15 '10 at 10:20
  • Apologies - didn't see that - I had another answer that worked - still +2rep for you (don't complain! ^_^ ) – Barrie Reader Sep 15 '10 at 10:21