1

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!

2
  • 4
    It should be Array, capital "A", or better yet just var input_array = []; Commented Nov 2, 2012 at 16:44
  • 1
    Also you should be declaring "id" and "url" with var !! Commented Nov 2, 2012 at 16:46

3 Answers 3

3

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 = [];
Sign up to request clarification or add additional context in comments.

3 Comments

or even var input_array = []
@HBP Yes, you can... :) Added it too! :)
forgot javascript is case sensitive!
1

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"));
}

3 Comments

I'm not sure that your query selector is correct. I believe next selects only the next sibling, while + * would select all elements that follow .category-description.
@Shmiddty: You're thinking of the ~ selector. :) The + selects only the next element sibling.
You're right. I tend to use the + selector in the context of li, so it ends up styling all elements but the first li, but only because each is immediately preceded by an li.
0

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");

1 Comment

It's OK in JavaScript for the index to be greater than the array length. The language explicitly supports that.

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.