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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 20

Thread: Use of arrays?

  1. #1
    New Coder
    Join Date
    Mar 2013
    Posts
    81
    Thanks
    45
    Thanked 0 Times in 0 Posts

    Use of arrays?

    So I’m learning javascript and practicing Arrays concept right now. I’ve totally understood, how to make one and whatnot..

    Look at this code, I know what it does. The only question I’ve is, where would it be used for?
    Just putting in data in the array makes no sense what so ever to me..

    Code:
    box = [];
    for(i=0; i <=10; i++){
    box[i] = i;
    console.log(box[i]);
    }
    Last edited by h123er2; 02-12-2014 at 10:23 PM.

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Not sure I understand what your question is.

    That code is just the old way of populating an array with the numbers 0 through 9 where each number goes in the position of the array corresponding to its value.

    The way you'd write that code for modern browsers is:

    Code:
    box = [];
    box.forEach(function(a, b) {a = b;console.log(a)});
    Loops are almost never needed for array processing in JavaScript any more.
    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.

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,460
    Thanks
    11
    Thanked 600 Times in 580 Posts
    Quote Originally Posted by felgall View Post
    The way you'd write that code for modern browsers is:

    Code:
    box = [];
    box.forEach(function(a, b) {a = b;console.log(a)});
    Loops are almost never needed for array processing in JavaScript any more.
    i wish it would, but that doesn't do anything because forEach skips over empty array slots, so even using Array(10) instead of [] won't help...


    i use this native way (no vars, user-functions, or loops) of populating a numerical array :
    Code:
    Object.keys(new String(Array(11))).map(Number);
    Last edited by rnd me; 02-12-2014 at 10:34 PM.
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%

  • #4
    New Coder
    Join Date
    Jun 2009
    Posts
    31
    Thanks
    7
    Thanked 1 Time in 1 Post
    I am also learning JavaScript and I think I have some idea what you are asking.

    For a very simple example, suppose there is a page with many '<p>' tags and you want to change text color or background color of them depending upon if they are odd or even.
    You can collect all row elements in an array and then using for loop over it change styles of alternate rows.

    please look at following example. we are collecting all 'P' tags in HTML Colection which is an array.

    I am also learning, so not sure if it is right way to do it.
    var paras = document.getElementsByTagName('p');
    var plength = paras.length;
    for (var i=0; i<=plength; i++){
    if(i%2==0 )
    paras[i].style.color = '#ff0000';
    else
    paras[i].style.color = '#0000ff';
    }


    try to run it in console on some webpages.
    In Firefox you can open console usinf 'CTRL+Shift+K',
    in chrome 'Ctrl+Shift+J' or 'F12'
    'F12' in Firefox opens firebug console if you have installed it.

    I ran it on https://github.com/adobe/brackets/wi...ck-on-Brackets

    hope it helps if you were asking for something like this.

  • Users who have thanked skywaves for this post:

    h123er2 (02-13-2014)

  • #5
    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 rnd me View Post
    i wish it would, but that doesn't do anything
    oops. Must not have been awake properly when I wrote that.
    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.

  • #6
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,460
    Thanks
    11
    Thanked 600 Times in 580 Posts
    in programming, you often need to store information. We put little chunks of info behind nicknames we refer to as variables. Sometimes we have not just one chunk, but many chunks of info. When you have a lot of info that is similar and related, an array can be used to group it all together behind a single nickname.

    Going back to the CD audio days, an apt analogy can be had considering an album vs a single, the album being an array of single tracks. Sometimes you want the whole album to just sit back and relax, and sometimes you want to jump right to a certain song. The array provides both capabilities; random-access and sequential access. This is much handier than having to swap 10 different disks to hear 10 different singles, or using 10 different variables to refer to that entire collection. It's so much better that folks began to construct/burn their own arrays of tracks under variable names like "driving mix", "dinner", "80s", etc...


    that's the motivation behind arrays: organization. Sometimes the data in them is unique, sometimes its "copied" into an "array" for convenience, like getElementsByClassName("hidden"). Sometimes arrays actually duplicate thier contents from other places and sometimes they act like tiny re-directs to the actual info contained in other places, but the commonality is that they make it easier to apply verbs to related nouns.

    traditionally those verbs were applied procedural-aly using loops, but as felgall mentions, there are much better 21st-century ways of handling such collections. Take a look at jQuery to see this power in action. jQuery's CSS selectors make it easy to grab a custom collection of tags from the DOM. Speaking loosely, a jQuery call returns an array of tags, but that's only half the magic. The real power is how it can apply verbs to all of the single tags at once. For example, we can express the behavioral outcome of skywave's code in much less code as higher-level terms using jQuery:

    Code:
    $("p:even").css('color', '#ff0000');
    $("p:odd") .css('color', '#0000ff');
    as you can see, the code is almost all nouns and verbs; no conjunctions, conditionals, or pronouns like you have with loops.

    you can use the same power on data as jQuery provides on tags by using the newer (5 years old at this point; time flies!) Array methods like [].map, [].filter, [].forEach, [].reduce, [].some, and [].every. I won't get into what each one does, but together they provide the modern programmer with a very slick and convenient way to express the intentions they have for data. If you want to leapfrog everyone around you, skip over procedural snooze fests like for loops and figure out how javascript's chaining works. It's different yes, but no more complicated than loops, and even if it were 50% harder to understand, it's 1000% better for you in the long run...
    Last edited by rnd me; 02-13-2014 at 03:07 AM.
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%

  • The Following 2 Users Say Thank You to rnd me For This Useful Post:

    h123er2 (02-13-2014), skywaves (02-13-2014)

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,303
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Quote Originally Posted by rnd me View Post
    i use this native way (no vars, user-functions, or loops) of populating a numerical array :
    Code:
    Object.keys(new String(Array(11))).map(Number);
    That works fine, but IMO it is difficult for a newcomer to understand. Especially Array(11) when 0-9 is wanted.
    And there is still a var in the array name - var x = Object.keys(new String(Array(11))).map(Number);

    Is there any real advantage in using such a construct as compared with the traditional (old-fashioned) loop which is pretty obvious?

    var box = [];
    for(i=0; i <=9; i++) {
    box[i] = i;
    }
    Last edited by Philip M; 02-13-2014 at 08:57 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.

  • #8
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    I do not see the point of load jQuery and Its 94 kb to write three or four statements !

    Code:
    var box=[],i=10;while (i--) box[i]=i;

  • #9
    Regular Coder
    Join Date
    Mar 2006
    Posts
    728
    Thanks
    35
    Thanked 132 Times in 123 Posts
    There are lots of ways to get an array of numbers from 0 to 10, but this is my favorite-

    Code:
    var box=[0,1,2,3,4,5,6,7,8,9,10];

  • Users who have thanked mrhoo for this post:

    Arbitrator (02-16-2014)

  • #10
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,460
    Thanks
    11
    Thanked 600 Times in 580 Posts
    Quote Originally Posted by Philip M View Post
    Is there any real advantage in using such a construct as compared with the traditional (old-fashioned) loop which is pretty obvious?

    var box = [];
    for(i=0; i <=9; i++) {
    box[i] = i;
    }
    well, that snippet creates an implicit global, which is not obvious to newcomers. I know that's easily fixable, but it underscrores my concerns about for loops in JS in a more general kinda of way. of course, both routines work, as do 5 others i'm sure.

    I would submit that there is nothing obvious about the for loop code; it's got a bunch of \W chars, some non verbs/nouns, a certain order of init params that's not obvious, and one only knows it because they learned a different language first. But prior familiarity works against them as well because they assume that it has it's own scope. I see loop issues comprising at least 10% of "why doesn't this work" type questions; the biggest single part of the JS core that actually screws people over and causes frustration.


    Now, i'm not saying scope is an issue here, as long as you use locals, which even senior coders can forget. My point in posting is just to illustrate an alternative. If you can work out how the functional approach works, you'll not only know about some kick-*** native methods, you'll be on the way to custom chaining, which IMO is JS's best feature and one that sets it apart from most other languages in a developer-friendly way. If a simple counter can show how functional works, hopefully newcomers will start on the 21st-century path instead of using procedural constructs i learned in BASIC.


    in short, there's little advantage either way; both have their ups and downs. But if you're gonna do it, why not do it in a way that encourages exploration into really powerful features rather than really boring and jargony features. I rarely use for-loops any more, and i guess this reflects with my newer problem-solving mindset rather than when i was wearing noob shoes. Maybe it's just a vain attempt to jump in front of the for-loop bullet that kills noob interest in JS and leads to mis-founded claims about the language being "broken".

    plus i figured there would be like 15 billion for loop examples out there; so why not tease some good code...
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%

  • #11
    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 007julien View Post
    I do not see the point of load jQuery and Its 94 kb to write three or four statements !

    Code:
    var box=[],i=10;while (i--) box[i]=i;
    Neither does anyone else here.

    Also why write three or four statements when one is all you need.

    Object.keys(new String(Array(11))).map(Number);

    A single statement written in plain JavaScript.
    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.

  • #12
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    Object.keys(new String(Array(11))).map(Number);
    A single statement written in plain JavaScript.
    Valable only (MDN) with Firefox 1.5(1.8) and IE 9 !

  • #13
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,303
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Quote Originally Posted by 007julien View Post
    Valable only (MDN) with Firefox 1.5(1.8) and IE 9 !
    Yes, so my old-fashioned traditional way using a loop works in all browsers.

    mrwho's var box=[0,1,2,3,4,5,6,7,8,9,10]; is fine for 10 elements, less so for 50 or 500.

    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.

  • #14
    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 007julien View Post
    Valable only (MDN) with Firefox 1.5(1.8) and IE 9 !
    It is a part of the current JavaScript standard released in 2011. Alll browsers that support JavaScript support those methods other than really antiquated browsers such as Firefox 1.0 - which is long dead.

    Microsoft didn't introduce support for JavaScript into Internet Explorer until version 9 which is why IE8 didn't support those JavaScript commands. IE8 only runs Microsoft's own JScript - which Microsoft discarded after IE9 so that language is now dead.

    You can easily add the extra methods yourself so as to support people using really antiquated browsers while still using modern code. Then once you no longer need to support tha really antiquated browsers you can delete the code you added specifically for them and have modern code.

    Anyway, there's no reason for anyone to still be running IE8. I had IE11 running on my Windows XP computer last year (before I replaced that somewhat antiquated computer with a more modern one).
    Last edited by felgall; 02-15-2014 at 08:56 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.

  • #15
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,460
    Thanks
    11
    Thanked 600 Times in 580 Posts
    Quote Originally Posted by Philip M View Post
    Yes, so my old-fashioned traditional way using a loop works in all browsers.
    so does a solution using Object.keys and [].map; both easily injected behind a conditional comment for our browser-challenged friends out there.

    Code:
    <!--[if lte IE 8]><script src='http://danml.com/js/compat.js'></script><![endif]-->
    you can wait for folks to upgrade their browser and js, or you can bring the upgrades to them (and only them) with just a few kb of code. Tools added into JS since 2007 were added for a reason, a good reason. Personally, i can't imagine doing anything worthwhile without them. Sure one can code like it's 1999, but given the choice, why would any serious programmer not want to use a fourteen-year newer set of tools?

    If such handy methods couldn't all be patched in <4kb of non-min'd code, i'd be very tempted to abandon IE8. It's dying pretty fast and i like to code for the future, not the past, because the future lasts longer and is more important. How do i know this? The image editor i wrote for "gran paradiso" in 2007 worked on the ipad when it came out years later... Had I insisted on catering to the Lowest Common Denominator, i wouldn't have an image editor, and a crucial job interview i had in 2009 might have gone very differently. It pays (literally in my case) to push the boundaries, especially when the risk is quantifiable. I just wish canvas was as easy to polyfill as [].map...

    Since it's harmless and mindless to teach old browsers these great new tricks (without imposing on browsers produced in the last five years) my abandonment temptations are practically moot.
    Last edited by rnd me; 02-15-2014 at 11:18 PM.
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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