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)
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>");
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
We all have baggage to carry in life, unfortunately for me I always get the trolley with the wonky wheel...
Code:
Youre = {
STILL_not_getting_it:function(){
alert("YOU, the original poster / thread starter NEED to POST the code and NOT a LINK.");
},
MissingThePoint:function(msg){
alert("You're missing the point. " + msg);
}
}
Youre.STILL_not_getting_it();
The Time Through Ages
In the Name of Allah, Most Gracious, Most Merciful
1. By the Time,
2. Verily Man is in loss,
3. Except such as have Faith, and do righteous deeds, and (join together) in the mutual enjoining of Truth, and of Patience and Constancy.
I am afraid that THIS is another example of an abuse of eval and why it gets such a bad name. eval should only be used as a last resort.
We all have baggage to carry in life, unfortunately for me I always get the trolley with the wonky wheel...
Code:
Youre = {
STILL_not_getting_it:function(){
alert("YOU, the original poster / thread starter NEED to POST the code and NOT a LINK.");
},
MissingThePoint:function(msg){
alert("You're missing the point. " + msg);
}
}
Youre.STILL_not_getting_it();
Bookmarks