/    Sign up×
Community /Pin to ProfileBookmark

For in Loop to calculate array values

Anybody able to offer any help…

[code=php]
function enterBook()
{
var myBooks = new Array()
var myPrices = new Array()

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)
{
document.getElementById(“total”).innerHTML =+ i;
}
}
[/code]

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!

to post a comment
JavaScript

6 Comments(s)

Copy linkTweet thisAlerts:
@pitikoJan 22.2013 — You can try this code:

<i>
</i>function enterBook()
{
var myBooks = new Array();
var myPrices = new Array();
var total = 0;
for (i = 1; i &lt;= 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] + "&lt;br /&gt;";
}
for (var i in myPrices)
{
total += myPrices[i];
document.getElementById("total").innerHTML = total;
}
}
Copy linkTweet thisAlerts:
@goose2013authorJan 22.2013 — Superb much appreciated!
Copy linkTweet thisAlerts:
@toicontienJan 22.2013 — 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.

<i>
</i>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 &lt; length; i++) {
alert("arr[" + i + "]=" + arr[i]);
}
Copy linkTweet thisAlerts:
@ReFreezedJan 22.2013 — You're missing a [FONT=courier new]var[/FONT] keyword before the [I]i[/I] in the for loop. Without it [I]i[/I] will become a global variable. Also, using the array literal notation ([FONT=courier new][][/FONT]) is shorter/faster/cleaner than writing [FONT=courier new]new Array()[/FONT], like so: [FONT=courier new]myArray = [];[/FONT] Just a general tip... Also note that [FONT=courier new]for (var ... in ...)[/FONT] 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 [I]myBooks[/I] and [I]myPrices[/I] 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:
<i>
</i>function enterBook()
{
var total = 0;
for (var i = 1; i &lt;= 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 + "&lt;br /&gt;";
total += price;
}
document.getElementById("total").innerHTML = total;
}


(Edit: woops, missed toicontien's reply ^^)
Copy linkTweet thisAlerts:
@TcobbJan 23.2013 — 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);
}[/CODE]


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.
Copy linkTweet thisAlerts:
@JMRKERJan 23.2013 — 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);
}[/CODE]


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.[/QUOTE]


Executing the above code ONLY will display nothing.

Modifying to show both key and value assignments will at least show something.
<i>
</i>&lt;script type="text/javascript"&gt;
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);
&lt;/script&gt;


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.
×

Success!

Help @goose2013 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...