Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-18-2013, 01:02 AM   PM User | #1
hiyatran
New Coder

 
Join Date: Jun 2010
Posts: 36
Thanks: 1
Thanked 0 Times in 0 Posts
hiyatran is an unknown quantity at this point
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
__________________
Daily Hot Deal
hiyatran is offline   Reply With Quote
Old 01-18-2013, 01:24 AM   PM User | #2
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,999 Times in 3,968 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 01-18-2013, 01:27 AM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,999 Times in 3,968 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 01-18-2013, 07:39 AM   PM User | #4
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,465
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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>
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 01-18-2013 at 07:46 AM..
felgall is offline   Reply With Quote
Old 01-18-2013, 08:33 PM   PM User | #5
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,999 Times in 3,968 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 01-18-2013, 08:58 PM   PM User | #6
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,999 Times in 3,968 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
__________________
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.

Last edited by Old Pedant; 01-18-2013 at 09:01 PM..
Old Pedant is offline   Reply With Quote
Old 01-18-2013, 10:37 PM   PM User | #7
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,465
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 01-18-2013 at 10:45 PM..
felgall is offline   Reply With Quote
Old 01-18-2013, 11:15 PM   PM User | #8
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,999 Times in 3,968 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Ummm...I *did* state
Quote:
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.
Old Pedant is offline   Reply With Quote
Old 01-19-2013, 12:52 AM   PM User | #9
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,465
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 01-19-2013 at 01:06 AM..
felgall is offline   Reply With Quote
Old 01-19-2013, 02:08 AM   PM User | #10
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,999 Times in 3,968 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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
Quote:
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.
Old Pedant is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:01 PM.


Advertisement
Log in to turn off these ads.