Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    New Coder
    Join Date
    Jun 2010
    Posts
    39
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Multi-Dimensional Array

    I have an array, called, "myArray". Inside this myArray are 4 more arrays, "m0, m1, m2, m3".
    How do I access all the elements in all the array?

    Here's my code, :
    Code:
    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    
    <body>
    <script>
    var m0 = [0, 1, 2, 3, 4];
    var m1 = [5, 6, 7, 8, 9];
    var m2 = [10, 11, 12, 13, 14];
    var m3 = [15, 16, 17, 18, 19];
    
    var myArray = [m0, m1, m2, m3];
    
    
    for (var i = 0; i < myArray.length; i++) {
        for (var j = 0; j < ("m"+i).length; j++) {
            document.writeln(myArray[i][j]);
        }
    }
    </script>
    </body>
    </html>

    This code only give me the first 2 elements in each array.
    But, I would like to get all the elements in all the arrays.

    tks

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,869
    Thanks
    79
    Thanked 4,418 Times in 4,383 Posts
    Code:
    for (var i = 0; i < myArray.length; ++i) 
    {
        var subArray = myArray[i];
        for (var j = 0; j < subArray.length; ++j) 
        {
            // *PLEASE* don't use document.writeln!!!
            document.writeln( subArray[j]);
        }
        document.writeln("");
    }
    You don't *HAVE* to do it like that. But it's much simpler.

    YOu can do it as:
    Code:
    for (var i = 0; i < myArray.length; ++i) 
    {
        for (var j = 0; j < myArray[i].length; ++j) 
        {
            // *PLEASE* don't use document.writeln!!!
            document.writeln( myArray[i][j]);
        }
        // again, don't use document.writeln
        document.writeln("");
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,869
    Thanks
    79
    Thanked 4,418 Times in 4,383 Posts
    You need to understand that
    Code:
    ("m"+i).length
    will be getting the length of the *STRINGS* "m1", "m2", etc.

    And EACH of those strings is indeed only 2 character long.

    So that's why you were getting only 2 elements per subarray.

    I don't know why you thought "m"+i would magically turn into one of your arrays. Just because a string contains the *NAME* of an array does not make it the same as the array.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Old Pedant View Post
    I don't know why you thought "m"+i would magically turn into one of your arrays. Just because a string contains the *NAME* of an array does not make it the same as the array.
    To magically turn them into the arrays they could have used window["m"+i].length which of course will only work while everything is in the global namespace - once the script is fixed to wrap everything inside a function so as to not clash with other scripts that magic conversion would break. myArray[i].length is of course the correct way to reference it so that it doesn't break when you change other code.

    To fix some of the obsolete coding as well as resolving the problem I'd write it as:

    Code:
    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    
    <body>
    <div id="answer"></div>
    <script>
    (function() {
    "use strict";
    var myArray, i, ii, j, jj, str;
    myArray = [[0, 1, 2, 3, 4],[5, 6, 7, 8, 9],[10, 11, 12, 13, 14],[15, 16, 17, 18, 19]];
    str = '';
    for (i = 0, ii= myArray.length; i < ii; i++) {
        for (j = 0,jj = myArray[i].length; j < jj; j++) {
            str += myArray[i][j] + ' ';
        }
    }
    document.getElementById('answer').innerHTML = str;
    })();
    </script>
    </body>
    </html>
    Last edited by felgall; 01-18-2013 at 07:46 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,869
    Thanks
    79
    Thanked 4,418 Times in 4,383 Posts
    While I grant you the theory of doing
    Code:
    for (i = 0, ii= myArray.length; i < ii; i++) {
    I find it really hard to believe that will make a difference that matters in about 99.7% of all JavaScript coding.

    There are times when doing things according to best practices is obviously superior (as in the way you teach us to use unobtrusive JavaScript, again in this example!), but there are other times where (as in this case) saving a few nanoseconds in a browser simply does not and will not matter except in the most extreme cases.

    In any case, I would bet that in practical terms my "trick" of doing
    Code:
        var subArray = myArray[i];
    and then working with that subArray variable saves at least as much time as assigning the array length to a variable does. While at the same time making the coding clearer. (And if I'm wrong about it saving more time, I think I'm still right about the clarity of the coding.)

    Anyway, all of this is truly moot for a newbie who is just struggling to understand multi-dimensional arrays in the first place.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,869
    Thanks
    79
    Thanked 4,418 Times in 4,383 Posts
    Okay...I just had to test my guess.

    I ran Felgall's looping code inside of a 1-million times outer loop and got (average of 5 runs) 750 milliseconds.

    I did the same with my code (using the subArray but *NOT* using the ii and jj variables to hold the array lengths) and the average of 5 runs was 780 milliseconds.

    Okay. So let's be complete about it. I then tried the original:
    Code:
        var str = "";
        for (var i = 0; i < myArray.length; ++i) 
        {
            for (var j = 0; j < myArray[i].length; ++j) 
            {
                str += myArray[i][j];
            }
        }
    HA!!! 735 milliseconds!!!

    **************

    So, NEITHER Fellgall's nor my "improvements" are actually improvements when it comes to performance! In fact, they each case a very slight but measurable DECREASE in performance.

    And, yes, my "improvement" is worse than Felgall's. So I eat crow on that.

    But, given the *VERY* negligible performance differences, I'd still opt for my subArray version just because of the clarity of coding. (I also strongly suspect that if we were doing something more complex with the sub-array element in that innermost loop my answer might show up better, but at this point I'm not going to bet on it.)

    **********

    All the tests were done with Chrome browser. Clearly you can expect different answers with different browsers.

    **********

    P.S.: Just for completeness, I tried moving the var declarations around. Putting them all at the start of the code vs. putting them inline in the code. Made no measurable difference in performance. Since I *VASTLY* disagree with Felgall and many other JavaScript pundits on the placement of var, and since I can now see it does not impact performance at all, I'm going to stick with putting them where I want them. Basically, the same way I would use them in other languages: Declare them where first used.
    Last edited by Old Pedant; 01-18-2013 at 09:01 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    I am not going to argue the performance issue - I simply automatically code my ascending loops that way because I find they are just as easy to read and maintain that way as the other way - using that code therefore costs me nothing and so the improved performance even though small is a free improvement. I would not worry about such small improvements if the code were made more complicated by doing so. I also wouldn't argue with anyone who codes it the other way.

    The difference in performance relates to the extra time JavaScript takes every time you reference something that has a dot between parts of the name and so providing an alias without the dot will always speed things up if the reference is being made multiple times. So with two or more iterations of the loop my version will always be a small fraction of a microsecond faster than yours.

    Quote Originally Posted by Old Pedant View Post
    P.S.: Just for completeness, I tried moving the var declarations around.
    No matter where you put the var declarations inside a function all the variables are declared before any of the code in the function runs. I simply put the statement that declares them in the same spot as JavaScript runs the declarations. There will be no performance difference if you put the vars elsewhere in the function because JavaScript always processes them first no matter where you put them.

    Placing the declarations at the point where they run rather than scattering them through the function is something that improves maintainability of the script for newbies who are unaware that declarations are always hoist to the top of their scope.

    Consider:

    Code:
    var x = 'global';
    function scopetest() {
    alert(x); // x is undefined at this point
    x = 5;
    alert(x);
    x = 'yes';
    alert(x);
    var x;
    }
    alert(x);
    scopetest();
    alert(x);
    With the var not at the top of the function a newbie would probably expect the commented alert to use the global copy of x and not the local one declared at the bottom of the function which at that point has been declared but not assigned a value.
    Last edited by felgall; 01-18-2013 at 10:45 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,869
    Thanks
    79
    Thanked 4,418 Times in 4,383 Posts
    Ummm...I *did* state
    Declare them [use the var keyword] where [each variable is] first used.
    Yes, I absolutely agree that your example is the pathological one. Confusing to most anyone if, for example, they were to use the same named variable for two purposes in a given function.

    But, if you followed my "where first used" pattern, you would write:
    Code:
    var x = 'global';
    function scopetest() {
        var x; // must be here before the first usage
        alert(x); // x is undefined at this point
        x = 5;
        alert(x);
        x = 'yes';
        alert(x);
    }
    alert(x);
    scopetest();
    alert(x);
    Yes, I could see that you *could* confuse a local variable with a global one if you aren't careful.

    But I can tell you, in 100% honesty, that I haven't mixed up a global and local variable in any language in AT LEAST the last 5 years. Quite probably longer than that, but I won't rely upon my memory for longer than that.

    Is that because, in real coding, I use *REAL* variable names? I wouldn't be surprised (That is, I never use single letter names for anything more than a for loop variable...and seldom even then and seldom even 2 letter names. I am prone to using row and col as names, I admit.) I tend to try to make my variable names self-documenting. Not so much when I post sample code snippets here, I admit. But in real coding? Yes.

    Oh...and I try to avoid global variables, again in any language. Sometimes they are unavoidable, but when I do use them you can bet they have a nice descriptive name. I'm convinced that sane variable names are more important than coding style, in most cases.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Old Pedant View Post
    Yes, I absolutely agree that your example is the pathological one.
    It does illustrate that it doesn't matter where in the function you declare the variable because the variable exists from the start of the function.

    Declaring where first used still conceals the fact that the variable still exists from the start of the function and isn't created at the point where you declare it. This is different from the way some other languages work where a variable is created when it is first used. I can't think of an example of where this makes a difference but it obviously does in some situations or the syntax checker at jslint.com wouldn't give a warning if you use multiple var statements in the one function.

    The other thing with declaring all the variables at the top is that it makes it easier to check which variables you have declared if the script fails to run because you try to use one that you forgot to declare. Declaring on first use with a 100 line function where you forgot to declare a variable means you need to search through the code to find the first use to add the 'var' and if you overlook the first couple then you could easily end up with code that is similar to my example where you add it to a later reference by mistake. It would be quite easy for someone used to writing historical JavaScript where variables didn't have to be declared to overlook declaring one and having their modern JavaScript refuse to run at all until they add the missing declaration. Having all the declarations in a single var at the top definitely makes it easier to spot whether a given variable is declared or not as you don't need to search the entire function looking for it.

    Consider the following:

    Code:
    (function() {
    "use strict"
    var myArray = [[0, 1, 2, 3, 4],[5, 6, 7, 8, 9],[10, 11, 12, 13, 14],[15, 16, 17, 18, 19]];
    for (var i = 0; i < myArray.length; ++i) 
    {
        var subArray = myArray[i];
        for (var j = 0; j < subArray.length; ++j) 
        {
            str = myArray[i][j];
            alert(str);
        }
    }
    })();
    That code will refuse to run in modern browsers because one of the variables is not declared but you don't have easy access to a list of which are declared. The error console will tell you the first variable that it found that you forgot to declare but will still not assist much in finding the first place it is used.

    Declaring on first use can also lead to confusing situations such as:

    Code:
    if (somecondition) var mynewvar = 'true condition text';
    else mynewvar = 'false condition text';
    A newbie would probably place a completely unnecessary var in front of the variable name on the second line not realising that the first line declares it even if that statement never runs.

    While none of these things confuse you as an experienced JavaScript programmer, it is far less confusing for newbies if they are taught to declare variables at the point where JavaScript is going to process the declarations.
    Last edited by felgall; 01-19-2013 at 01:06 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,869
    Thanks
    79
    Thanked 4,418 Times in 4,383 Posts
    You make good points, as usual. (Should I say, "as always"?)

    I don't think the missing var str in the your example is the best illustration of the possible problem. Certainly Chrome, for example, says
    Uncaught ReferenceError: str is not defined
    Hard to misunderstand that error.

    Hmmm...What does MSIE say?

    ***WOW!!*** MSIE 9 allows it!!!!

    I didn't realize that MSIE 9 didn't pay attention to "use strict"!

    No wonder I do all my debugging in Chrome! <grin/>

    Well, you certainly have made your point, at least for those who still use MSIE for coding /debugging!!!
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •