I'm just learning JavaScript through a Lynda.com tutorial, and I'm trying to push myself beyond some of the examples in each chapter.
Right now I'm on arrays. One of the examples they went through was adding all of the values in the array:
Code:
var myArray = [500, 500, 500, 500, 500];
var total = 0;
for ( var i = 0; i < myArray.length; i++ ) {
total = total + myArray[i];
}
document.write("The total is: " + total);
Okay so I understand this. My challenge, which I can't seem to solve by myself, is this: What if I had an array with 6 values, and I wanted to add the first two numbers, then subtract the third? And loop through this each time.
For example:
Code:
var myArray = [35, 250, 75, 60, 90, 100];
My desired output would be:
210 (result from 35 + 250 - 75)
260 (result from 210 + 60 + 90 - 100)
What are some ways I could accomplish this?
Thank you!
John
11-25-2011, 04:46 PM
xelawho
hmmm... I suspect that this is not what you are looking for,but it may be of interest anyway. You can access array values directly by their position in the array:
var myArray = [],i,sign=1;
for (i=0;i<2000;i++) myArray[i] =1/(2*i+1);
var alternatedTotal = 0,oldAlternatedTotal;
for ( var i = 0; i < myArray.length; i++ ) {
oldAlternatedTotal=alternatedTotal;
alternatedTotal += sign*myArray[i];
sign =- sign;
}
document.write("<p>The alternatedTotal is : " + alternatedTotal+" and<br>"+(4*alternatedTotal)+"< Pi <"+(4*oldAlternatedTotal)+"</p>");
And you notice that Pi/4 = 1-1/3+1/5-1/7+1/9....
11-25-2011, 07:46 PM
JMRKER
Another alternative solution...
Code:
<html>
<title></title>
</head>
<body>
<script language="javascript">
var myArray = [35, 250, 75, 60, 90, 100];
var sum = 0;
var total = 0;
for (var i=0; i<myArray.length; i=i+3) {
sum = myArray[i]+myArray[i+1]-myArray[i+2];
total += sum;
alert(sum+' : '+total);
}
alert('Total: '+total);
</script>
</body>
</html>
11-26-2011, 12:38 AM
hollywoodjrc
Thank you, everyone, for your time! This is extremely helpful.
Kindly,
John
11-26-2011, 04:09 PM
JunkMale
Another method might include...
Code:
var myArray = [35, 250, 75, 60, 90, 100];
// add first two and then subtract the third & repeat...
modVal = myArray.length / 2;
for(c=0,total=0; c<myArray.length; c++)
total += ( (c+1)%modVal == 0 )? -(myArray[c]) : myArray[c];
alert(total);// outputs 260
11-26-2011, 05:07 PM
Ayşe
Code:
<script type="text/javascript">
var B = ["+","+","-","+","+","-"];
var A = [35, 250, 75, 60, 90, 100];
var str = "";
for(var i=0; i< A.length; i++) {
str += B[i] + A[i];
}
alert( "str = " + str ); // +35+250-75+60+90-100