tracer tong
tracer tong

Reputation: 553

javascript fails when populating array

When I run the following javascript, it fails when input_array[input_array.length] = id; is not commented out. Can anyone see what is causing this?

function cat_images_low_lag () {
    var input_array = new array ();

    cat_images = $(".category-description").next().find("img");
    cat_images.each(function () { 
        url = $(this).parent().attr("href");
        id = url.split("id=");
        id = id[1];

        input_array[input_array.length] = id;
    });
    alert ("trst");
    alert(input_array.join("\n"));
}   

cheers!

Upvotes: 1

Views: 66

Answers (3)

I Hate Lazy
I Hate Lazy

Reputation: 48761

Others noted the capitalization problem, but since you're using jQuery, a nicer way to build the Array is like this:

function cat_images_low_lag () {
    var input_array = $(".category-description + * img").map(function () { 
        return this.parentNode.href.split("id=")[1];
    }).toArray();

    alert ("trst");
    alert(input_array.join("\n"));
}

Upvotes: 1

Travis J
Travis J

Reputation: 82287

Your initialization of the array is incorrect

var input_array = new array ();

You should use the shorthand

var input_array = [];

or

var input_array = new Array();

Moreover, to avoid having cat_images be a variable in the global scope, you may want to consider scoping it locally like this

var cat_images = $(".category-description").next().find("img");

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

First thing, replace:

var input_array = new array ();

With:

var input_array = new Array();

And use this to insert:

input_array.push(id);

Or directly add:

input_array[input_array.length] = id;

Other ways to initialize arrays:

var input_array = [];

Upvotes: 3

Related Questions