1

I am trying to use 2 dimensional array in javascript for storing strings. But I am not able to get the values correctly. Below is my code.

      var commentstore=new Array();
        function creating(id,day)
        {
            if(commentstore[day,id] != null)
         {
             alert("It already exists: commentstore["+day+"]["+id+"]"+commentstore[day,id] );
             var textinput="<div id='closeit'>Comments:<input type='text' name='comm["+day+"]  ["+id+"]' value='"+commentstore[day,id]+"'/></div>
                               <div id='closing' onclick='closecomment("+id+","+day+")'>:)</div>";
         }
            else
            {
                var textinput="<div id='closeit'>Comments:<input type='text' name='comm["+day+"]  ["+id+"]' /></div>
                               <div id='closing' onclick='closecomment("+id+","+day+")'>:)</div>";  
                $('#comm').html(textinput);
            }

    function closecomment(id,day)
    {
        comm.style.visibility='hidden';
        var str='comm['+day+']['+id+']';
        var element = document.getElementById(str);
     if(element.value !=null)
     {
      commentstore[day,id]=element.value;
      alert('New values stored: commentstore['+day+']['+id+']'+commentstore[day,id]);
     }
    }

So in the above code if commentstore[0,0]='man' then commentstore[1,0] and [2,0] and [3,0] ....[7,0] are also filled with 'man'. Same thing is happening with commentstore[0,1] even commentstore[4,1] scenarios. Can any one please provide any tutorial or sample code where we can dynamically create javascript 2d arrays. Thanks in advance.

2
  • [day,id] is equivalent to just doing [id] Commented Dec 28, 2009 at 15:45
  • Thank you all for helping. It is now working fine. I need to verify it more. Thanks again.. Commented Dec 28, 2009 at 15:58

3 Answers 3

6

Replace commentstore[day,id] with commentstore[day][id]. That's the syntax for multi-dimensional arrays.

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

2 Comments

It is not working for me in the line if(commentstore[day,id] != null) . So I used ','. Is this because of IE.
Please describe what isn't working, and whether you're getting any error messages.
1

Use commentstore[0][0] instead of commentstore[0,0]. Also, use strict comparaison whenever loose comparaison is not needed:

var commentstore = [];

function creating(id,day)
{
    if(commentstore[day] === undefined) commentstore[day] = [];
    if(commentstore[day][id] !== undefined)
    {
        alert("It already exists: commentstore["+day+"]["+id+"]"+commentstore[day][id] );
        var textinput="<div id='closeit'>Comments:<input type='text' name='comm["+day+"]  ["+id+"]' value='"+commentstore[day][id]+"'/></div>
                       <div id='closing' onclick='closecomment("+id+","+day+")'>:)</div>";
    }
    else
    {
        var textinput="<div id='closeit'>Comments:<input type='text' name='comm["+day+"]  ["+id+"]' /></div>
                       <div id='closing' onclick='closecomment("+id+","+day+")'>:)</div>";  
        $('#comm').html(textinput);
    }

function closecomment(id,day)
{
    comm.style.visibility='hidden';
    var element = document.getElementById(str);
    if(element.value !== '')
    {
        commentstore[day][id]=element.value;
        alert('New values stored: commentstore['+day+']['+id+']'+commentstore[day][id]);
    }
}

edit: in the original code, str is undefined and the execution fails. You can fix it in closecomment with:

var element = $('#closeit > input').eq(0);

2 Comments

Thanks. This is giving error as object required at if(element.value) line. And alert is not coming in closecomment function
Indeed, str is undefined. You have to find the relevent input. Either by walking the DOM, or by identifying to input.
-1

JavaScript only supports arrays with a single index but the index can be anything, so if you really want two dimensional arrays, do this:

commentstore[day+','+id] = ...

i.e. use a string with to components as the key.

4 Comments

Why on earth would you not use a proper multi-dimensional array? a = []; a[0] = []; a[0][1] = ...
For example because of the initialization issue: You must create an array per index. With my solution, you can just assign anywhere. Also, my solution allows for arbitrary keys (not only integer) and sparse arrays. In a word, it's slower but generally more simple to use and understand and debug.
It's inefficient if you need to parse every record at a given index in the first dimension.
@Alsciende: "inefficient"? Smells like premature optimization to me. With the new JIT compilers in the browsers, you won't notice a difference and it will make your code much more simple. What's worth more? 12ms in millions of browsers or a week of your time tracking down obscure bugs?

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.