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 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jun 2018
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Issue returning the new array from a simple push

    As you can see I am a newb trying to learn some JS, but i feel like I am trying to learn carpentry with a broken tape measure.

    All I want to do is get this code to return a new array that is each element in the arr2 array -1, so in this case [0,1,99,3]

    I believe this code should work, but when I try to view the result in the console I am getting an error that result is not defined (when i have result = [] within the for loop) or an empty array (when I have result = [] outside of the loop). I cant learn anything without seeing my result so grateful for any help.


    I got the sample from here.
    https://coderbyte.com/video/loops-in-javascript



    Code:
    var arr2 = [1,2,100,4]
       
    
    for (i = 0; i < arr2.lenght; i++){
        result = []
        resule.push(arr2[i] - 1)
        console.log(result)
    }
     
    
    console.log(result)

  2. #2
    Master Coder sunfighter's Avatar
    Join Date
    Jan 2011
    Location
    Washington
    Posts
    7,611
    Thanks
    34
    Thanked 1,029 Times in 1,026 Posts
    Use the map() function:

    Code:
    var arr2 = [1, 4, 9, 16];
    
    var arr1 = arr2.map(x => x -1);
    
    console.log(arr1);
    OR decrement each element with a loop like your were trying:
    Code:
    <script>
    var arr2 = [1,2,100,4];
    var arr1 = [];
    
    for(var i = 0; i < arr2.length; i++) {
        arr1.push(arr2[i] - 1);
    }
    
    console.log(arr1);
    </script>
    Last edited by sunfighter; 06-11-2018 at 07:25 PM.
    Evolution - The non-random survival of random variants.
    Physics is actually atoms trying to understand themselves.

  3. #3
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Location
    Here
    Posts
    3,760
    Thanks
    58
    Thanked 678 Times in 673 Posts
    You want it outside the loop (otherwise it resets on every iteration) and you want arr2.length, not arr2.lenght. JavaScript is like every tough English teacher you have ever had, combined, when it comes to spelling mistakes.

    Learning how to use your browser's builtin error console may help in reducing that broken tape measure feeling.


 

Tags for this Thread

Posting Permissions

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