Jump to content
Larry Ullman's Book Forums

Chapter 6: Working With Arrays, Page 201 Multidimensional Arrays


Recommended Posts

I was working on a simple for loop to emulate the the given example on page 201, the labeled box "MULTIDIMENSIONAL ARRAYS". The example actually shows how to loop through the subarray, but instead I just wanted to loop through the top level array for simplicity.

 

Here is a similar example but with different values in the array:

 

function process() {

       'use strict';

       var message = '';
       var terran = [['marine', 'marauder', 'reaper'], ['battlecruiser', 'banshee', 'raven']];

       var output = document.getElementById('output');


       for (var i = 0, count1 = terran.length; i < count1; i++) {

               message = terran[i];
       }

       if(output.textContent !== undefined) {
               output.textContent = message;
       } else {
               output.innerText = message;
       }

}

window.onload = process;

And then the object element to output:
<div id="output"></div>

 

When the script is run, this is what it outputs:

 

battlecruiser,banshee,raven

 

Is this the correct result? The script is returning the second element in the array.

 

 

Thanks!

Mark

Link to comment
Share on other sites

An SCII fan, I see.

Anyway, the reason you're getting that is because of the following line in your code:

 

message = terran[i];

 

I think we discussed this before in another post, but because you're using just =, not +=, the first value stored in message in the for loop is overwritten by the second value.

 

Also, you are technically storing an array in message, which is then displaying itself as you described because of the way the browser chooses to display arrays assigned to the DOM.

I would recommend looping through both dimensions of the array to get better control of the multidimensional array and the ability to better process it.

 

Lastly, please put your code in code tags from now on, so that it's easier to read.

Thank you.

  • Upvote 1
Link to comment
Share on other sites

major sc2 fan, looking forward to heart of swarm.

 

I might of gotten confused with how php arrays are handled, although there are some major differences between php(which I have yet to figure out) and javascript, I took a chance and used similar syntax.

 

in PHP a similar loop would have been fine wouldn't it? See below:

 


echo $message = terran[$i];

 

in javascript, concatenation is handled a little different as you mentioned the first value is overriden by the second value. But as you advised, below works now:

 


message += terran[i];

Link to comment
Share on other sites

While you can echo a variable assignment to the screen in PHP, it's not a best practice to do so. The following (while the same result), is desirable:

 

$message = $terran[$i];
echo $message;

 

Also, if $terran[$i] is an array, the word "Array" will be echoed to the screen by PHP, not the values in the array.

 

The way JS is designed though, if you use the += operator to add an array to an array, the resulting value will be a string. As a demonstration:

 

var terran = [['marine', 'marauder', 'reaper'], ['battlecruiser', 'banshee', 'raven']];

var message = terran[0];

alert(typeof message); // Alerts "object" because message is an array at the moment.

message += terran[1];

alert(typeof message); // Alerts "string" because it's the only way JS knows how to handle an array added to an array using the += operator.

document.getElementById('output').innerHTML = message; // Alerts the string "marine,marauder,reaperbattlecruiser,banshee,raven".

 

Hopefully that clarifies things.

Link to comment
Share on other sites

Thanks Hartley, you've pointed out a lot of things to learn from. I am really just trying to understand the difference in storing array values with php and javascript.

 

As I have tested with a simple array (no longer the multidimensional for simplicity sake), I finally grasp the concept now.

 

In PHP:

 



<?php

$terran = array('marine', 'marauder', 'reaper');


for ($i = 0; $i < 3; $i++) {


echo $terran[$i];

}

?>

 

In Javascript:

 




function process() {

'use strict';

var message = '';
var message2 = '';

var terran = ['marine', 'marauder', 'reaper'];

var output = document.getElementById('output');
var output2 = document.getElementById('output2');

for (var i = 0, count1 = terran.length; i < count1; i++) {

message = terran[i]; // Will print out the last value in the array.

message2 += terran[i]; // Will print out all the values.

}


if(output.textContent !== undefined) {
output.textContent = message;
} else {
output.innerText = message;
}

if(output2.textContent !== undefined) {
output2.textContent = message2;
} else {
output2.innerText = message2;
}


 

Looping through arrays in Javascript is different from PHP in that it seems to add values to a variable, whereas in PHP values are stored. In Javascript array values are overridden as new values get assigned, but in PHP array values do not. Is this what is going on?

 

Thanks for your patience, your help much appreciated.

Link to comment
Share on other sites

Looping through arrays in JS and PHP isn't that different (if really at all, conceptually).

I think the point you might be getting caught on is the use of the += operator.

 

Just to think about it from a conceptual point, let's say I have the following variable assignment:

 

var txt = 'Hey there!';

 

Now imagine (and don't worry about the actual code yet) that I wanted to add an array to that txt variable above. How would you do that? Somehow, something doesn't seem right, right? It just seems intuitively weird to add an array as is to a string. As a result, when you try to add an array to a string, JS falters a bit, as it's not quite sure what to do.

 

Actually, let me rephrase that, JS knows exactly what to do, because it's been designed a certain way by programmers, but even those programmers I think were a bit confused on how to handle an array being added to a string. For whatever reason (and I don't think it's an unreasonable solution), the designers of JS decided that whenever you add an array to a string, internally, without you knowing about it, JS would convert each of the values in the array to a string, place the string ", " between each value, and then concatenate that entire string onto the end of whatever.

 

Taking this a bit further, when you use the += operator on a variable that already is a string or undefined (i.e., without a value yet), then JS defaults to the aforementioned behavior of "stringifying" the array and concatenating it onto whatever is already there. That's why you're getting the output you're getting when you use the += operator.

 

To be honest though, you should never add an array to a variable with the +=. That fact that you get any output at all is merely a consequence of the JS designers requiring that something other than an error occur. If you want to get all the values in an array and do something with them, the proper way is to loop through the array. There's really no other way.

 

In the case of your multidimensional array example, you really have no (reasonable) choice but to put a nested loop within a loop to access all the individual values (as opposed to the array structures).

 

I hope that clears things up. More than anything, just be careful in differentiating between the = operator and the += operator, as there still seems to be some confusion (not to embarrass you or anything).

  • Upvote 1
Link to comment
Share on other sites

 

Taking this a bit further, when you use the += operator on a variable that already is a string or undefined (i.e., without a value yet), then JS defaults to the aforementioned behavior of "stringifying" the array and concatenating it onto whatever is already there. That's why you're getting the output you're getting when you use the += operator.

 

To be honest though, you should never add an array to a variable with the +=. That fact that you get any output at all is merely a consequence of the JS designers requiring that something other than an error occur. If you want to get all the values in an array and do something with them, the proper way is to loop through the array. There's really no other way.

 

 

I got confused with what you're saying here at first, with you should never add an array to a variable with +=. But I'm assuming you mean its okay to add an array to a variable (using the += operator) if we are looping through an array.

 

In the case of your multidimensional array example, you really have no (reasonable) choice but to put a nested loop within a loop to access all the individual values (as opposed to the array structures).

 

I hope that clears things up. More than anything, just be careful in differentiating between the = operator and the += operator, as there still seems to be some confusion (not to embarrass you or anything).

 

I'm glad you read my mind here, the route of having no choice to access all individual values is where I was getting at. The nested loop is absolutely required. Not embarassed at all, thanks for your time. Always a pleasure.

Link to comment
Share on other sites

Again, just to clarify, you can use the += operator to add "array values" together, as they're simply number/string/Boolean values, but don't use the += operator to add "array structures" together. In other words, always properly loop through arrays, regardless of how many dimensions there are.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...