user823527
user823527

Reputation: 3712

Javascript two-dimensional array

I want to create a two dimensional array in a javascript function. I found code that should do that but doesn't. I declare the array then define a function to add elements to the array which are also arrays.

    // Array function
    var card_array = new Array();
    function card_array(card_id, card_top, card_left) {
        alert('array');
        this.card_id = card_id;
        this.card_top = card_top;
        this.card_left = card_left;
    }

    // Toggle LinkCard minimize/expand
    function toggle_linkcard(toggle, card_id) {

        var icard = 0; 
        $('.linkcard').each(function () {
            card_top = $(this).position().top;
            card_left = $(this).position().left;
            card_i = $(this).attr('id');
            card_array[card_array.length++] = new card_array(card_i, card_top, card_left);
            icard++;
        });
        alert(card_array);

    }

The line of code where I add elements to the array breaks the code.

            card_array[card_array.length++] = new card_array(card_i, card_top, card_left);

What should I fix in that?

Upvotes: 1

Views: 1886

Answers (3)

Rodolphe
Rodolphe

Reputation: 1731

Just change this line:

var card_array = new Array();

into:

var my_card_array = new Array();

And this one:

card_array[card_array.length++] = new card_array(card_i, card_top, card_left);

into:

my_card_array.push(new card_array(card_i, card_top, card_left));

And of course, change the alert.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754575

The problem here is that you have two values with the same name: card_array

  • A variable named which is initialized to a new Array()
  • A function which takes 3 parameters

The function declaration happens last and hence wins. So when you execute the expression card_array[card_array.length++] you are doing so on a function instance, not an array.

To fix this change the function name to a unique name.

Upvotes: 2

melihcelik
melihcelik

Reputation: 4599

You defined the function's name as card_array, same name as the variable's. So after that line of code, you don't have any variable named card_array, only the function. Try changing your variable or function name.

Upvotes: 2

Related Questions