SitePoint Sponsor

User Tag List

Results 1 to 12 of 12
  1. #1
    SitePoint Member
    Join Date
    Sep 2006
    Location
    San Diego
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Array Question from a Noob

    Arrays are confusing me.

    When you type a number to a text field to search in an array, does it look for the exact number you typed or does it count the number of array items?

    EXAMPLE QUESTION:
    When I type in the number 12, does it look for the number 12 like this (aryMonths[12] ) , OR does it count 12 times, starting at zero?

    If I start from 0 and count 12 times it still takes me to December. Why does this code have return aryMonths[NUM-1];

    CODE EXAMPLE:

    <input type="button" value="Convert to Dollars" onclick="EnterMonth();">

    Function MonthAsString(NUM)
    {
    var aryMonths = new Array();
    aryMonths[0] = "January";
    aryMonths[1] = "February";
    aryMonths[2] = "March";
    aryMonths[3] = "April";
    aryMonths[4] = "May";
    aryMonths[5] = "June";
    aryMonths[6] = "July";
    aryMonths[7] = "August";
    aryMonths[8] = "September";
    aryMonths[9] = "October";
    aryMonths[10] = "November";
    aryMonths[11] = "December";

    return aryMonths[NUM-1];
    }

  2. #2
    Avid Logophile silver trophy
    ParkinT's Avatar
    Join Date
    May 2006
    Location
    Central Florida
    Posts
    2,283
    Mentioned
    181 Post(s)
    Tagged
    4 Thread(s)
    In your example, the value you pass to the function is the index of the array. That means if you pass "6", it will reference arryMonths[6].
    Because, from a human perspective, you want to retrieve a month by its position in the calendar (1 for January, 2 for February, and so on) the returned value must be the index passed MINUS ONE. This compensates for the fact that the array is zero-indexed.

    You could, very easily, do this instead
    PHP Code:
    Function MonthAsString(NUM)
    {
    var 
    aryMonths = new Array();
    aryMonths[0] = "******INVALID*****";
    aryMonths[1] = "January";
    aryMonths[2] = "February";
    aryMonths[3] = "March";
    aryMonths[4] = "April";
    aryMonths[5] = "May";
    aryMonths[6] = "June";
    aryMonths[7] = "July";
    aryMonths[8] = "August";
    aryMonths[9] = "September";
    aryMonths[10] = "October";
    aryMonths[11] = "November";
    aryMonths[12] = "December";

    return 
    aryMonths[NUM];

    And that would make the code a bit simpler to understand without changing its behavior.

    Of course, good defensive programming practice requires a test of the input Range.
    So the first line in your function should be something like this:
    PHP Code:
    if (NUM 0) || (NUM 12)
       return 
    "INVALID ARRAY INDEX"
    Last edited by ParkinT; Jun 15, 2012 at 05:05. Reason: Clarified Defensive Programming practice
    Don't be yourself. Be someone a little nicer. -Mignon McLaughlin, journalist and author (1913-1983)


    Literally, the best app for readers.
    Make Your P@ssw0rd Secure
    Leveraging SubDomains

  3. #3
    SitePoint Member
    Join Date
    Sep 2006
    Location
    San Diego
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for responding!

    >> That means if you pass "6", it will reference arryMonths[6]. >>
    Is it matching Index numbers or counting down array objects?
    So that means, when I type 6, I'm asking asking JavaScript to find the index number 6, i.e., find an exact match between the string "6" typed in the form to the 6 in the bracket [6])? There is no counting then, just matching index numbers?

    Here's how I was wondering how the javascript processes the command.
    YOUTUBE:

  4. #4
    Under Construction silver trophybronze trophy AussieJohn's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    776
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Hey there,

    When you reference an index in an array, in English that would read "Get me the item at this position in the array".

    If we want to think of an analogy for an array, let's think of it as a set of P.O. boxes at your local post office, you're the postmaster that's delivering mail. You might have mail for PO Box 123, you have an overview of all the PO Boxes and you can see exactly where #123 is located, so you go straight to it. Next up is mail for #132, again - you know exactly where it is - you don't need to count all the boxes up until the correct number.


    In practice, let's take your array of months for example and you call aryMonths[4] you will get the item at index 4 (which would be May, because arrays are 0-indexed).

    When you return the value in your return statement the following happens:

    Code javascript:
    return aryMonths[NUM-1]; //this is what you see
     
    //let's say you have MonthAsString(4)
    //this ends up being:
    return aryMonths[4-1];
     
    //what actually happens is:
    return aryMonths[3]; //It's important to note that the calculation happens first. 
     
    /* 
     just to add to this a little, 
     if you wanted to know the last item in an array you would subtract 1 from the array length.
     in this case, the array length is 12, which means the last index is 11. Handy if you have a 
     dynamically populated array whose length you don't know
    */
     
    //last item:
    aryMonths[ aryMonths.length - 1];



    So in short. someArray[n] will always directly reference an index in an array, not iterate over all items until it reaches the correct one.
    var details = {
    . . web: "afterlight.com.au",
    . . photos: "jvdl.id.au",
    . . psa: "usethelatestversion.com"
    }

  5. #5
    Avid Logophile silver trophy
    ParkinT's Avatar
    Join Date
    May 2006
    Location
    Central Florida
    Posts
    2,283
    Mentioned
    181 Post(s)
    Tagged
    4 Thread(s)
    Viewing your video I have a better understanding of your question*.
    Let me clarify something you asked; There is no 'counting' of the array defined in your function. That array could be defined outside the function and the behavior would be the same. As a matter fact, since this is javascript, the use of the 'var' keyword - although inside the function - explicitly made that array global in scope.

    All the interpreter 'responds to' is the last line (in this case the return) where is 'references' the array.

    Code:
    Function MonthAsString(NUM)
    {
        return aryMonths[NUM-1];
    //having been passed NUM, the interpreter simply uses it as the index INTO the array.  In this case, the NUM value passed in has been modified and that mathematical change is applied BEFORE the array is referenced to return a value
    }
    By the same token, the 'modification' of the index could take many forms. Try to wrap your head around this (admittedly peculiar) scenario
    Code:
    Function MonthAsString(NUM)
    {
      aryIndices = new Array();
      aryIndices[0] = 0
      aryIndices[1] = 0
      aryIndices[2] = 1
      aryIndices[3] = 2
      aryIndices[4] = 3
      aryIndices[5] = 4
      aryIndices[6] = 5
      aryIndices[7] = 6
      aryIndices[8] = 7
      aryIndices[9] = 8
      aryIndices[10] = 9
      aryIndices[11] = 10
      aryIndices[12] = 11
      aryIndices[13] = 12
    
      aryMonths = new Array();
      aryMonths[0] = "January";  
      aryMonths[1] = "February";
      aryMonths[2] = "March";
      aryMonths[3] = "April";
      aryMonths[4] = "May";
      aryMonths[5] = "June";
      aryMonths[6] = "July";
      aryMonths[7] = "August";
      aryMonths[8] = "September";
      aryMonths[9] = "October";
      aryMonths[10] = "November";
      aryMonths[11] = "December";
    
      return aryMonths[aryIndices[NUM]];
    }
    Off Topic:


    *BTW: The use of video like that was a very clever idea. For a complex problem or detailed question I can see it as a great way to convey your message
    Don't be yourself. Be someone a little nicer. -Mignon McLaughlin, journalist and author (1913-1983)


    Literally, the best app for readers.
    Make Your P@ssw0rd Secure
    Leveraging SubDomains

  6. #6
    SitePoint Member
    Join Date
    Sep 2006
    Location
    San Diego
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ParkinT View Post
    All the interpreter 'responds to' is the last line (in this case the return) where is 'references' the array.
    Keleth wrote me on another forum but didn't explain why the interpreter repsonds to the last line where it sees a "return". (BTW. What do you call a 'return'?) He wrote a nice example:
    "As for accessing the index, precedence is a big deal, just like math. If you have 4 * (3 + 6 / 2 * (9 - 3)) you have order of precedence, in that you look at the inner most parenthesis first, then head outwards. In the same way, code is always by order of precedence, in that inner most code is computed first (most often) and then outer code. "
    Question: So, "return" is the inner most code in precedence, like his above example? Is there a rule of precedence in JavaScript I can read somewhere?

    He further wrote:
    "So if you have monthArray[NUM - 1] first it figures out NUM - 1 (the inner set of code). It doesn't care that its looking for an array index yet, it just knows NUM - 1 has to be calculated. So then it realizes that for NUM = 12, that is 11, so it goes out a layer and sees monthArray[11], and realizes, oh, this is an array, let me try to pull the value of monthArray indexed at 11."
    He said, "it just knows NUM - 1 has to be calculated"

    Question: Why does the interpreter have to calculate that first? Is there a rule of precedence in JavaScript I can read somewhere?


    Quote Originally Posted by ParkinT View Post
    Off Topic:


    *BTW: The use of video like that was a very clever idea. For a complex problem or detailed question I can see it as a great way to convey your message
    Exactly. It can save a lot of time clarifying. It's like asking another developer to come over to your station for help

  7. #7
    SitePoint Member
    Join Date
    Sep 2006
    Location
    San Diego
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by AussieJohn View Post
    //what actually happens is:
    return aryMonths[3]; //It's important to note that the calculation happens first.

    So in short. someArray[n] will always directly reference an index in an array, not iterate over all items until it reaches the correct one.
    Why does the calculation happen first, since the JS Interpreter works from top to down? Is it because Return statements ALWAYS have precedence?

  8. #8
    Avid Logophile silver trophy
    ParkinT's Avatar
    Join Date
    May 2006
    Location
    Central Florida
    Posts
    2,283
    Mentioned
    181 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by LoveFest View Post
    Why does the calculation happen first, since the JS Interpreter works from top to down? Is it because Return statements ALWAYS have precedence?
    I think you are misinterpreting this statement (and I blame the English language).
    That 'calculation' is performed when the interpreter gets to that line. However, the interpreter realizes that the index value must be resolved. So it first determines what that value is before looking for that index.
    In other words, this would work also

    PHP Code:
    return aryMonths[subtract(NUM1)]; 
    assuming you defined the function "subtract" like this
    PHP Code:

    function subtract(anumbnum) {
      return 
    anum bnum;

    Does that clarify it in your mind or make it more confusing?
    Don't be yourself. Be someone a little nicer. -Mignon McLaughlin, journalist and author (1913-1983)


    Literally, the best app for readers.
    Make Your P@ssw0rd Secure
    Leveraging SubDomains

  9. #9
    SitePoint Member
    Join Date
    Sep 2006
    Location
    San Diego
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ParkinT View Post
    That 'calculation' is performed when the interpreter gets to that line. However, the interpreter realizes that the index value must be resolved. So it first determines what that value is before looking for that index.Does that clarify it in your mind or make it more confusing?
    That's the confusing part: The interpreter goes from top down. So, it seems logical that it 1. goes through the array, grabs the string ('March'), 2. then hits the Return statement, performs the operation on the index number (subtraction), 3. but then has to jump back up and pull down the correct string, 'February'. How else would the interpreter know an index [2] is February, unless it jumps back up and searches the indexes again?

    Keleth said,
    "As for accessing the index, precedence is a big deal, just like math. If you have 4 * (3 + 6 / 2 * (9 - 3)) you have order of precedence, in that you look at the inner most parenthesis first, then head outwards. In the same way, code is always by order of precedence, in that inner most code is computed first (most often) and then outer code. So if you have monthArray[NUM - 1] first it figures out NUM - 1 (the inner set of code). It doesn't care that its looking for an array index yet, it just knows NUM - 1 has to be calculated. So then it realizes that for NUM = 12, that is 11, so it goes out a layer and sees monthArray[11], and realizes, oh, this is an array, let me try to pull the value of monthArray indexed at 11."
    So, my question is from that if "It doesn't care that its looking for an array index yet, it just knows NUM - 1 has to be calculated," then it logically seems to make sense that the JS interpreter does not always go from top down, it goes first and foremost by precedence like a math problem with parenthesis around the numbers.

  10. #10
    Under Construction silver trophybronze trophy AussieJohn's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    776
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by LoveFest View Post
    That's the confusing part: The interpreter goes from top down. So, it seems logical that it 1. goes through the array, grabs the string ('March'), 2. then hits the Return statement, performs the operation on the index number (subtraction), 3. but then has to jump back up and pull down the correct string, 'February'. How else would the interpreter know an index [2] is February, unless it jumps back up and searches the indexes again?

    Variables are just some data stored at a specific place in memory, and the variable name is a convenient alias to that location in memory (beats writing something like 0x00000000c4 instead of 'x', right?).


    So when you write arrMonths[2] you aren't finding something in arrMonths but rather you are referencing something in memory


    Quote Originally Posted by LoveFest View Post
    So, my question is from that if "It doesn't care that its looking for an array index yet, it just knows NUM - 1 has to be calculated," then it logically seems to make sense that the JS interpreter does not always go from top down, it goes first and foremost by precedence like a math problem with parenthesis around the numbers.

    And there you've pretty much stumbled upon how a lot of interpreters / compilers work. They don't read lines from left to right like we do


    When the interpreter gets to a line with parentheses (e.g. for a calculation), it will always try to resolve operations inside of the parentheses before applying that value to the overall calculation.


    e.g. something like:
    Code:
    someThing = 2 * (5+2);

    Here, of course the parentheses are necessary because if they weren't present they would give a different outcome. (Depending of course on what you're calculating.)


    The interpreter will see the parentheses and go "ok, I'll find the matching one and perform all the operations inside of it before continuing up the line".


    It of course doesn't matter if you're using values or variables, the order of execution stays the same:


    Code:
    x = 2;
    y = 5;
    someThing = x * (y + 2);
    var details = {
    . . web: "afterlight.com.au",
    . . photos: "jvdl.id.au",
    . . psa: "usethelatestversion.com"
    }

  11. #11
    SitePoint Member
    Join Date
    Sep 2006
    Location
    San Diego
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by AussieJohn View Post
    And there you've pretty much stumbled upon how a lot of interpreters / compilers work. They don't read lines from left to right like we do
    The interpreter will see the parentheses and go "ok, I'll find the matching one and perform all the operations inside of it before continuing up the line".
    The question for me wasn't that interpreters reads from LEFT to RIGHT, but from TOP to DOWN and how it was resolving this function and how what was the order process.

    So to summarize, you're saying in the line of code below, the interpreter looks at the whole function as a block of code, and then first looks inside all parenthetical statements first, and resolves them first, and then start back at the top again and goes down to the array?

    The interpreter sees [NUM-1]; first and resolves it, and then goes back up to the top and starts again?

    PHP Code:
    Function MonthAsString(NUM)
    {
    var 
    aryMonths = new Array();
    aryMonths[0] = "January";
    aryMonths[1] = "February";
    aryMonths[2] = "March";
    aryMonths[3] = "April";
    aryMonths[4] = "May";
    aryMonths[5] = "June";
    aryMonths[6] = "July";
    aryMonths[7] = "August";
    aryMonths[8] = "September";
    aryMonths[9] = "October";
    aryMonths[10] = "November";
    aryMonths[11] = "December";

    return 
    aryMonths[NUM-1];


  12. #12
    SitePoint Member
    Join Date
    Sep 2006
    Location
    San Diego
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by LoveFest View Post
    The question for me wasn't that interpreters reads from LEFT to RIGHT, but from TOP to DOWN and how it was resolving this function and how what was the order process.

    So to summarize, you're saying in the line of code below, the interpreter looks at the whole function as a block of code, and then first looks inside all parenthetical statements first, and resolves them first, and then start back at the top again and goes down to the array?

    The interpreter sees [NUM-1]; first and resolves it, and then goes back up to the top and starts again?
    OK. That last post above was incorrect. Pedant, on CodingForums gave me a really thorough and clear walk-through: "JS sees the declaration var aryMonths, so it puts 'aryMonths' into an internal table as the name of a known variable. " It just simply allocates the array to memory, pointing to each one (using POINTERS). No commands are made yet; just storing to memory. Then in the order of precedence, the translator sees the [NUM-1], subtracts one from the variable NUM, and then sees it's part of an array. It grabs the POINTER that is in that element number and runs off to see what it points to. It brings back a string in this case, and finally sees the command to return the "value of that string to the caller of the function". So clear now!


Bookmarks

Posting Permissions

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