www.webdeveloper.com
Results 1 to 7 of 7

Thread: For in Loop to calculate array values

  1. #1
    Join Date
    Jan 2013
    Location
    London, UK (Originally Vancouver)
    Posts
    10

    For in Loop to calculate array values

    Anybody able to offer any help...

    PHP Code:
    function enterBook()
    {
        var 
    myBooks = new Array()
        var 
    myPrices = new Array()
        
        for (
    1<= 5i++)
        {
            
    myBooks[i] = prompt("Enter title of book","");
            
    myPrices[i] = parseFloat(prompt("Enter price of book",""));
            
    document.getElementById("output").innerHTML += ". " myBooks[i] + ". Price: " myPrices[i] + "<br />";
        }
        
        for (var 
    i in myPrices)
        {
            
    document.getElementById("total").innerHTML =+ i;
        }

    I need to calculate the total of the myPrices array values using the 'for in' loop and display them to my page, i think im pretty close

    Thanks!

  2. #2
    Join Date
    Jan 2009
    Location
    Sao Paulo, Brazil
    Posts
    15
    You can try this code:

    Code:
    function enterBook() 
    { 
        var myBooks = new Array();
        var myPrices = new Array(); 
        var total = 0;
        for (i = 1; i <= 5; i++) 
        { 
            myBooks[i] = prompt("Enter title of book",""); 
            myPrices[i] = parseFloat(prompt("Enter price of book","")); 
            document.getElementById("output").innerHTML += i + ". " + myBooks[i] + ". Price: " + myPrices[i] + "<br />"; 
        } 
        for (var i in myPrices) 
        { 
    		total += myPrices[i];
            document.getElementById("total").innerHTML = total; 
        } 
    }

  3. #3
    Join Date
    Jan 2013
    Location
    London, UK (Originally Vancouver)
    Posts
    10
    Superb much appreciated!

  4. #4
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,774
    You do not want to use a for-in loop to iterate over an Array object. A for-in loop serves a very different purpose: It iterates over all the properties in an object. You want to use a regular loop when iterating over an Array.

    Code:
    var obj = {
      a: "foo",
      b: 123
    };
    
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) { // filter out properties that do not exist on "obj" but exist in its prototype chain
        alert(key + "=" + obj[key]);
      }
    }
    
    var arr = ["foo", 123];
    
    for (var i = 0, length = arr.length; i < length; i++) {
      alert("arr[" + i + "]=" + arr[i]);
    }

  5. #5
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    You're missing a var keyword before the i in the for loop. Without it i will become a global variable. Also, using the array literal notation ([]) is shorter/faster/cleaner than writing new Array(), like so: myArray = []; Just a general tip... Also note that for (var ... in ...) is used to iterate through the members of an object and generally not to loop through an array.

    Finally, if you're not using the values in the myBooks and myPrices arrays later in your script then you don't need any arrays here - you can just combine your two loops and save the values returned from the prompts in temporary variables inside the loop:
    Code:
    function enterBook()
    {
        var total = 0;
        for (var i = 1; i <= 5; i++)
        { 
            var title = prompt("Enter title of book","");
            var price = parseFloat(prompt("Enter price of book","")); 
            document.getElementById("output").innerHTML += i + ". " + title + ". Price: " + price + "<br />";
            total += price;
        }
        document.getElementById("total").innerHTML = total;
    }
    (Edit: woops, missed toicontien's reply ^^)

  6. #6
    Join Date
    Mar 2009
    Posts
    512
    Just to add to the previous comments:
    (1) For-In loops are slower than the "normal" for loops
    (2) A javascript array is an object, and it has various properties that are functions. If you have:

    Code:
    var a = [];  //create empty array
    var i;
    for(i in a){  //display all properties
        alert(i);
    }
    You will see a lot of stuff that aren't numerical values at all. If you try adding them to
    "total" you will get a very bizarre result that you don't want at all.

  7. #7
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,415

    Lightbulb

    Quote Originally Posted by Tcobb View Post
    Just to add to the previous comments:
    (1) For-In loops are slower than the "normal" for loops
    (2) A javascript array is an object, and it has various properties that are functions. If you have:

    Code:
    var a = [];  //create empty array
    var i;
    for(i in a){  //display all properties
        alert(i);
    }
    You will see a lot of stuff that aren't numerical values at all. If you try adding them to
    "total" you will get a very bizarre result that you don't want at all.
    Executing the above code ONLY will display nothing.
    Modifying to show both key and value assignments will at least show something.
    Code:
    <script type="text/javascript">
    var a = [];  //create empty array
    a['a'] = 1;
    a['b'] = 2;
    a['c'] = 3;
    
    var i;
    var sum = 0;
    for(i in a){  //display all properties
        alert(i+' '+a[i]);
        sum += a[i];
    }
    alert('Sum: '+sum);
    </script>
    Note: If you have any methods attached to the 'a' array, they would show as well,
    which would not be what you might expect for the summation portion of your question.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

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
  •  
HTML5 Development Center



Recent Articles