2

So I wanted to write a if else statement where if Array.isArray is false, display a message. The function I have below allows user to enter an address, click Find ZipCode and does it thing. The function works, it just that if I input an invalid address, it doesn't show the message I wanted, which is invalid zipcode

In my HTML, I have:

<label>
Address:
      <input name="address" type="text" id="address"></label>
      <input type="button" value="Find ZipCode" id="find">
<p id="output"></p> 

and Javascript:

var hello = function(data) {
    var result = ""; // empty string to hold the value
    var address = $("#address").val();

    if (! Array.isArray(data))
    {
        $("#output").html("invalid zipcode");
    }
    else {
        for (var i = 0; i < data.length; i++) 
        {
            var zipcode = data[i].zipcode;
            result += address + " zipcode: " + zipcode;
        }
    $("#output").html(result);

    }
};

$("#find").click(function(){
    var address = $("#address").val();
    $("#output").html("Loading...");            
    $.getJSON("zipcodelookup.php", "address="+address , hello);  
});

3 Answers 3

3

Unless you modified the Array.prototype there is no Array.isArray method. I think what youre looking for is $.isArray.

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

2 Comments

ES5 adds an isArray method to Array. The noticeable exception to browsers which don't support this is IE < 10, however, it can be trivially polyfilled.
+1 $.isArray is definitely what the OP had in mind (or should use) since jQuery is already imported.
0

You could also test like this to see if it's an Array:

function isArray(arr) {
    return Object.prototype.toString.apply(arr) === '[object Array]';
}

Comments

0

Testing for types in Javascript to infer other conditions is often a bad idea. It seems that in this case, if the zip code is found, then an array (of something) is returned.

You are therefore concluding that if you don't get an array, the zip code wasn't found. That isn't particularly robust, it would be better for the server to return a defined message or error code that was more helpful, e.g. it could advise if the zip code wasn't found, the input was invalid or the database isn't available.

You can also do tests on the returned array to see if it has the features you want (i.e. use feature detection).

Comments

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.