Web Analytics Made Easy -
StatCounter Simple array question - CodingForum

Announcement

Collapse
No announcement yet.

Simple array question

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Simple array question

    Hi

    Im relativley new to javascript and would like to now if i have an array, for example:

    var area = ['NG1','NG2','NG3','NG4','NG5']

    and i have a variable which is captured from a text input box for example:

    var location = document.form1.location.value.

    how do i compare 'location' against 'area' to confirm wether the variable appears in the array.

    Thanks for any help

  • #2
    Use array.indexOf
    You'd need to add a small/extra javascript code(which is provided in the above page) to make it for IE.
    Digitalocean Cloud Hosting (Referral link - get $10 free credit) Fameco

    Comment


    • #3
      Or as an alternative:-


      Code:
      <script type = "text/javascript">
      
      var area = ['NG1','NG2','NG3','NG4','NG5'];
      var found = false;
      var location = document.form1.location.value;
      for (var i = 0; i<area.length; i++) {
      if (area[i] == location) {
      found = true;
      alert ("The location " + location + " was found at area[" + i + "]");
      }
      }
      if (!found) {
      alert ("The location " + location + " was not found");
      }
      
      </script>


      “Sex is one of the most wholesome, beautiful and natural experiences that money can buy.” - Steve Martin

      All the code given in this post has been tested and is intended to address the question asked.
      Unless stated otherwise it is not just a demonstration.

      Comment


      • #4
        Or, as another dirt simple alternative:
        Code:
        var area = new Array( );
        area["NG1"] = 1
        area["NG2"] = 2
        area["NG3"] = 3
        area["NG4"] = 4
        area["NG5"] = 5
        
        var found = area[ document.form1.location.value ];
        if ( found == null ) alert("Not found")
        else  alert("found at " + found);
        ?? No??
        Yes, I know there's a more compact form for initializing the array. But the above code shows clearly how an associative array works.
        Be yourself. No one else is as qualified.

        Comment


        • #5
          That's more confusing than simple alternative. There are no associative arrays in Javascript. You use object and its properties to construct something similar to associative array, but it isn't the same.

          Even though you used var area = new Array( ); to initialize it, area will not behave as an array. Javascript array methods will not work well with it. In PHP count($area) would return 5 as expected, but in Javascript area.length will show 0.

          When indexes are integers naturally you use arrays, but when you have indexes that are strings, use object and its properties.
          Code:
          var area = {NG1:1, NG2:2, NG3:3, NG4:4, NG5:5}

          Comment


          • #6
            I'm sorry, but I have to disagree. If that "array" I showed isn't an associative array, I'd sure like to know what it really is! You want to call it an "indexed collection," instead? Okay, fine.

            But look here:
            http://en.wikipedia.org/wiki/Associative_array

            I quote:
            Associative arrays can be implemented in any programming language as a package and many language systems provide them as part of their standard library.
            ...
            In PHP and JavaSript all arrays can be associative, except that the keys are limited to integers and strings.
            So maybe this is a case of you say "to-may-to" and I say "to-mah-to" but I'd sure like to know what you would call a JavaScript "array that is indexed by a string."

            ********

            And I never said that an array USED as an associative array would have all the properties we ordinarily associate with standard arrays. Dunno where you drew that conclusion from. In point of fact, the associative array is much more powerful than a standard array, depending on what it is used for.
            Last edited by Old Pedant; Apr 6, 2009, 11:54 PM.
            Be yourself. No one else is as qualified.

            Comment


            • #7
              Interesting. I googled "javascript associative arrays" and found a ton of other people who apparently don't like calling them by that moniker. (And another ton of people like myself who are puzzled by all the hoopla.)

              Not sure why not. When I learned JS back in the dark ages (1998-1999) that's all we called them. Seems the "language lawyers" are quibbling about the fact that they don't have *ALL* the characteristics of "TRUE" associative arrays. Ehhh...sorry, but I'm pragmatic. If it walks like a duck, quacks like a duck, and swims like a duck, I'm willing to ignore the fact that it has fur instead of feathers.
              Last edited by Old Pedant; Apr 7, 2009, 12:16 AM.
              Be yourself. No one else is as qualified.

              Comment


              • #8
                i think the complaints about that relate to how you are using the array as an object.

                if that's the case, you should probably use an objectObject instead.

                this will make it easier to duck-type later, and avoids dredging up array prototypes when iterating the object.

                That said, you could use a new String, new Date, or =function(){}, all JS objects can be used like the associative arrays you see in other languages.
                Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

                Comment


                • #9
                  Ahhh...now *THAT* is a succinct and cogent argument!

                  Yes, I hadn't thought about the fact that changes to the standard array prototype would affect an "associative array." NOW I see razor's point. Sorry to be so obtuse.

                  Isn't that fascinating? Stuff we never thought about back in the dark ages. We were just happy to find that JS supported a built-in dictionary type, as we thought of it.

                  Okay, I'm convinced.

                  Still, then, with the syntactic change given by razor (and, yes, the necessary change in the semantics), that still strikes me as the easiest answer to the original question:
                  Code:
                  var area = {NG1:1, NG2:2, NG3:3, NG4:4, NG5:5} 
                  var found = area[ document.form1.location.value ];
                  if ( found == null ) alert("Not found")
                  else  alert("found at " + found);
                  Hard to write the code much smaller than that.
                  Be yourself. No one else is as qualified.

                  Comment


                  • #10
                    A suggested improvement (which I left out of my script above):-

                    var found = area[ (document.form1.location.value).toUpperCase() ];

                    This is another example of a thread where a beginner posts a very basic question which can be satisfied with a very simple solution, which then degenerates into a fierce argument between experts about the precise definition of associative arrays or whatever. I would have thought that stufran would be totally bemused and perhaps frightened off for good. He only wants to check that a few postcodes are within his delivery area! There is no point in introducing him to concepts far beyond his present ability level.

                    The days when compactness was a significant virtue and every byte counted passed away with the Commodore 64. Nor in most cases is speed of processing of more than academic interest these days. If script A takes 2 milliseconds but script B requires 4 milliseconds, for myself I can live with that.

                    One of the most important characteristics of any piece of code is clarity and simplicity. I am reminded of the electronics expert who always proposes to use a device involving six transistors, four diodes and eight capacitors to perform the function of an ordinary on-off toggle switch. It may work but it is quite OTT in the context.
                    Last edited by Philip M; Apr 7, 2009, 04:02 AM.

                    All the code given in this post has been tested and is intended to address the question asked.
                    Unless stated otherwise it is not just a demonstration.

                    Comment


                    • #11
                      @Philip: I wouldn't call that ''degeneration''. OP got 3 solutions [2.5 maybe] to choose from, and then the thread evolved into discussion. OP can walk away satisfied with a solution he picks, and we can discuss some details of the language, which certainly can improve our own understanding of it. We're not introducing him to anything, but if he's really interested in Javascript, he can read and learn, and if he isn't - he's got his fix. Not that bad, IMHO.
                      And when you say ''clarity and simplicity'' - have to say Pedant's last code is much more clear and simple than yours [his 2 var declarations and simple if/else vs. yours 4 vars, 1 loop and 2 if statements ]

                      @Old Pedant: I'm not a ''language lawyer'' [or an ''expert'' as Philip said], I just wanted to point out a simple fact that adding some properties to an object doesn't exactly make it an associative array in Javascript, though it does look similar.
                      Imagine you're coming from PHP background and see your first script, certainly you'd assume it is an associative array and methods of Array object can be used on it. Which simply isn't true. C'mon, you're a pedant, you don't like that kind of mess, right?
                      And I never said that an array USED as an associative array would have all the properties we ordinarily associate with standard arrays. Dunno where you drew that conclusion from. In point of fact, the associative array is much more powerful than a standard array, depending on what it is used for.
                      You didn't say that, and I wasn't saying that you did. I just made a comment about possible confusion arising from initializing an object as an Array, when it really isn't an array [OK, it is in your first script, but empty, and with few properties added to it].

                      I wasn't commenting out of concern for Array prototype but to clarify some issues and advise a better way of dealing with the question of associative arrays in Javascript [Object instead of Array].
                      Extending Array prototype wouldn't affect that ''associative array'' all that much, only maybe while enumerating properties/trying to use new methods that don't account for string-based ''index''.
                      I assume that at the time someone gets to extending built-in objects, he'd know that ''associative array'' in Javascript is only an Object with some properties, and if he doesn't know, he'd soon discover it while coding.

                      Here's something to think about during the weekend - a custom Javascript object which will be an associative array, with methods etc.

                      Comment


                      • #12
                        may i ask what is a moniker? the only moniker i know is the domain name registrar

                        Comment


                        • #13
                          Originally posted by sgsavvy View Post
                          may i ask what is a moniker? the only moniker i know is the domain name registrar
                          define:moniker
                          Digitalocean Cloud Hosting (Referral link - get $10 free credit) Fameco

                          Comment


                          • #14
                            Razor: Yes, I freely admit I was dead wrong. This is one of those cases where it's just something I've never needed to do any other way, so I got stuck doing it the first way I learned.

                            I misunderstood your argument about array semantics, because I completely forgot about such things as Array.prototype and beyond.

                            I won't say I learned something new by all this; I just unlearned something old that I had gotten wrong in the first place.

                            And Philip: Yes, mea culpa. Sorry for helping degenerate the thread. In my own defense, I'll only plead that it's not the speed of the code that I was caring about, it was the simplicity. Of course, in the process, I just made it more complex instead of simpler. *sigh*
                            Be yourself. No one else is as qualified.

                            Comment

                            Working...
                            X