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.
Results 1 to 6 of 6

Thread: Array Help

  1. #1
    New Coder
    Join Date
    May 2011
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Array Help

    OK so I am trying to put together a function that takes an array and then takes the square root of each number in old array and writes to the screen the new array of squared numbers. Not looking for answer, just what I need to do for the logic in the for statement.

  • #2
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    Firefox and other Gecko-based browsers have the Array.prototype.map method implemented. So usage is very simple:
    Code:
    var a = [1, 2, 3, 4, 5];
    var b = a.map(function(v)
    {
        return Math.sqrt(v);
    });
    
    alert(a);
    alert(b);
    There is very simple emulation for Internet Explorer. Usage is the same as shown above:
    Code:
    Array.prototype.map = function(fun)
    {
        var result = [];
        for (var i = 0, L = this.length; i < L; i++) {
            result.push(fun(this[i]));
        }
        return result;
    };

  • #3
    New Coder
    Join Date
    May 2011
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Is there a more elementary way of writing this? This would be something that an advanced user would use.

  • #4
    Banned
    Join Date
    Feb 2011
    Posts
    2,699
    Thanks
    13
    Thanked 395 Times in 395 Posts
    Quote Originally Posted by whteout View Post
    Is there a more elementary way of writing this?
    yep there is.

    Post the code you have so far and we can try to help you get it working.

  • #5
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    - send the array (let's call it old array) as an argument to a function

    within that function:
    - create a blank new array
    - loop trough the elements of the old array
    - rise each element to its square value
    - assign the square values as the elements of the new array
    - return the new array
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #6
    New Coder
    Join Date
    May 2011
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Got it

    Thanks


  •  

    Posting Permissions

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