1

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?

3 Answers 3

2

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.

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

1 Comment

Also, you can eliminate some code clutter by doing a card_array.push() instead of card_array[card_array.length++].
2

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.

1 Comment

That was the problem. Thanks.
0

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.

1 Comment

Thanks. I changed the variable name and switched to .push(). This works.

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.