JavaScript - Javascript Loops Performance
Hi,
Which among the following for iterating objects in JavaScript is better in terms of performance & usage? A) property enumeration: for (var propName in someObject) { var value = someObject[propName]; } B) Array protocol for (var i=0; i<someObject.length; i++) { var value = someObject[i]; } C) forEach method Can forEach method be used across various browsers and OS? K Similar TutorialsHello. I have a page that has bunch of moving elements, and obviously I want the movement to be smooth. It worked just great in chrome, but very chunky in firefox. I ran a profiler, found the bottleneck and dealt with it, so things work fine now, but after seeing the result of profiler I now have few questions: The function that is responsible for moving elements around takes 33% of time. Here's the code: Code: Tile.prototype.relocate=function(x,y){ this.elem.style.left=this.x=x; this.elem.style.top=this.y=y; } It's called from timer (setInterval) for elements that are not where they should be (they have .style.position set to "relative"). Is there a better way of moving elements around? Another function: Code: function type(code){ return code>>8; } It takes 13% of time. Now this is just ridiculous. 181854 binary shifts take 174.579ms. Is there a way to make it look like a function call but just replace the call with actual code at compile time, just like C's preprocessor? I have a nice javascript slideshow but it kills the rendering speed of my home page. According to Yahoo performance guru(s), javascript gets run before other stuff is rendered, so you fix that by putting the js code "at the end" of the html file. Putting it at the end puts the slideshow at the bottom which is not the desired result. And even abs positioning is slave to the <div> structure. How do I nullify the flow just for this one thing (I don't want to make the whole page absolute). Or is there a better way to fix the performance issue. Thanks. Qatrix is a new kind of JavaScript library for easily building up high performance web application with less code. And now is released today. The features of Qatrix a Hardware Accelerated Animation Qatrix will use the native CSS3 transition to process the animation as possible. And this kind of native basic process operation will enable hardware acceleration by browser. The animation of Qatrix will be more faster and more smoother. High performance code Qatrix is using more native code and special design to increase the performance. Web application will run much more faster and more efficient. Easy-to-learn The name of functions on Qatrix is familiar with the most popular JavaScript jQuery. It will be much more easy to use without re-learn other new concept and knowledge. Cache system Qatrix included a simple cache system to storage and fetch data with high speed. Incredible size Only 6KB compressed and gzipped file size with 60+ functions. Load script instantly without expectation. Read more and download: http://qatrix.com Hello all. I've spent a few days now browsing this forum along with guides on the net, I'm new to JS and I'm having a bit of trouble with loops. I just don't seem to get them, I was wondering if anyone had any tips or methods (the simpler the better ) for getting these learnt and done with? Would appreciate any tips Thanks This is a final loops in an exercise here is my code Code: <script type="text/javascript"> var counter; for (counter=0; counter<amount.length; counter++) {} { document.writeIn(counter+"<br/>"); document.writeIn("<tr><td>"date"[counter]"</td>"); document.writeIn("<td class = 'amt'>myArray</td>"); document.writeIn("<td>"firstName[counter]"</td>"); document.writeIn("<td>"lastName[counter]"</td>"); document.writeIn("<td>"street[counter]"<br />"); document.writeIn("<td>"+street[counter]+" "+city[counter]+" "state[counter]+" "+zip[counter]+"</td></tr>); Total=total+amount[counter]; document.writeIn("<table>"); } </script> This is what i have, what do i need to do to make this more proper and written properly? thanks Hi guys, I am new to learning javascript and have a test tomorrow on for loops. I know the answers to the three following loops but i wondered if anyone could take the time to explain to me how to find the answer from the code as I have no idea on how to find the answers (the answer is what is displayed in the alert). Many thanks, Mike The loops are these three: 1. var a=4;b=6; for(var c=0;c<=a;c++){b=b+c;} alert(b); (answer is 16) 2. var v=1; for(i=1;i<5;i++) for(j=2;j<5;j++) v+=1; alert(v); (answer is 13) 3. var s=0; for(i=0;i<=8;i++) if((i%2)==0)s+=1; alert(s); (answer is 5) We have created this function with loops and arrays Problem is the loops work only when I take out the function when the function is in place, nothing works, it is part of exercise anyone have suggestions here is my code Code: title>Congressional Races</title> <link href="results.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="votes.js"></script> <script type="text/javascript"> function totalVotes(votes){ var total=0; for (var i = 0; i <votes1.length; i++) { total = total + votes1[i]; } document.write(total); } </script> } </head> <body> thanks all who can help This is driving me crazy. I simply want to display the values of the checkboxes with a specific name. This loop executes only once, then stops, showing no error msg. I have found no similar problem elsewhere on the net and have done a ton of tests, but cannot find out why it won't continue to loop. I've included the whole html file. Please Help! Code: <HTML> <SCRIPT language="JavaScript"> function test1() { var chkLen=document.frmTable.CHK0.length; for (k=0;k<chkLen;k++) { //execution stops after one loop. no error msg. document.write(document.getElementsByName('CHK0')[k].value); } } </SCRIPT> <FORM NAME=frmTable> <TABLE BORDER=1> <TR> <TD><INPUT TYPE=CHECKBOX NAME=CHK0 VALUE='one'>1</TD> <TD><INPUT TYPE=CHECKBOX NAME=CHK0 VALUE='two'>2</TD> <TD><INPUT TYPE=CHECKBOX NAME=CHK0 VALUE='three'>3</TD> </TR> </TABLE><BR> <INPUT TYPE=BUTTON VALUE='Go' onClick=test1()> </FORM> </HTML> I want to learn javascript and I found codecademy.com which seems like a great way to learn the language. Before the first lesson it says Quote: You should be comfortable with loops, if statements, functions, and objects before attempting this course. Can someone explain what these are or point me in the direction where I can find the answers? I tried searching with google, but I havent found anything that clearly states what exactly the loop, object, etc. is. Hi, I ve recently come across the Advanced jQuery background image slideshow by Marco Folio. I have implemented it fine but when it goes to load an image I get a black screen for a second or two. I have about 15 images and reading around I found out that it has to do with the loading of images and that it would be better adding an image preloader to it. I have tried several pre loaders and have got the to work on their own, but not with this slider. This is the script.js Code: var slideshowSpeed = 6000; // Variable to store the images we need to set as background // which also includes some text and url's. var photos = [ { "title" : "", "image" : "1.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "2.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "3.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "4.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "5.jpg", "url" : "#", "firstline" : "", "secondline" : "" },{ "title" : "", "image" : "6.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "7.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "8.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "9.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "10.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "11.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "12.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "13.jpg", "url" : "#", "firstline" : "", "secondline" : "" }, { "title" : "", "image" : "14.jpg", "url" : "#", "firstline" : "", "secondline" : "" } ]; $(document).ready(function() { // Backwards navigation $("#back").click(function() { stopAnimation(); navigate("back"); }); // Forward navigation $("#next").click(function() { stopAnimation(); navigate("next"); }); var interval; $("#control").toggle(function(){ stopAnimation(); }, function() { // Change the background image to "pause" $(this).css({ "background-image" : "url(images/btn_pause.png)" }); // Show the next image navigate("next"); // Start playing the animation interval = setInterval(function() { navigate("next"); }, slideshowSpeed); }); var activeContainer = 1; var currentImg = 0; var animating = false; var navigate = function(direction) { // Check if no animation is running. If it is, prevent the action if(animating) { return; } // Check which current image we need to show if(direction == "next") { currentImg++; if(currentImg == photos.length + 1) { currentImg = 1; } } else { currentImg--; if(currentImg == 0) { currentImg = photos.length; } } // Check which container we need to use var currentContainer = activeContainer; if(activeContainer == 1) { activeContainer = 2; } else { activeContainer = 1; } showImage(photos[currentImg - 1], currentContainer, activeContainer); }; var currentZindex = -400; var showImage = function(photoObject, currentContainer, activeContainer) { animating = true; // Make sure the new container is always on the background currentZindex--; // Set the background image of the new active container $("#headerimg" + activeContainer).css({ "background-image" : "url(images/" + photoObject.image + ")", "display" : "block", "z-index" : currentZindex }); // Hide the header text $("#headertxt").css({"display" : "none"}); // Set the new header text $("#firstline").html(photoObject.firstline); $("#secondline") .attr("href", photoObject.url) .html(photoObject.secondline); $("#pictureduri") .attr("href", photoObject.url) .html(photoObject.title); // Fade out the current container // and display the header text when animation is complete $("#headerimg" + currentContainer).fadeOut(function() { setTimeout(function() { $("#headertxt").css({"display" : "block"}); animating = false; }, 500); }); }; var stopAnimation = function() { // Change the background image to "play" $("#control").css({ "background-image" : "url(images/btn_play.png)" }); // Clear the interval clearInterval(interval); }; // We should statically set the first image navigate("next"); // Start playing the animation interval = setInterval(function() { navigate("next"); }, slideshowSpeed); }); and this is the part of the html where it is added: Code: <div id="header_top"> <div id="headerimgs"> <div id="headerimg1" class="headerimg"></div> <div id="headerimg2" class="headerimg"></div> </div> </div> I would like to load 2 images on page load and then while it is displaying the 2 images to download to the browser cache the rest. Could you point me in the right direction. Thanks Hello everyone! Im new here so any help you can give would be great. I am a Designer, and some time AS3 programer. Teaching my self Javascript for a portfolio website. The Goal: I created a code that randomly creates and Populates Divs in a regular grid, then populates them with an image (using css backgroundImage property) or a print CMY(and Green) color. (eventually will include a shadow box and side scroller) The Problem: The creation and population works just fine, the first time around. if I "Refresh" the page (which i thought destroyed all vars and data) the page loads some times, or freezes. Some times it doesn't load at all! so its very unpredictable, obviously i need this to work the same way every time. Im pretty sure its something simple that i missed, a nuance of javascript or something. So if any one who is more experienced can help I would be super grateful!! here is the page on my website: designchangeseverything.com/beta/divpoptest.html here is the code (i included some of my comments so you can see how i was trying to debug): Code: <SCRIPT LANGUAGE="JavaScript"> var Tborder = .05 var howmanyIMG = 15 var winHeight = Math.floor(window.innerHeight); var winWidth = Math.floor(window.innerWidth); var BoxHeight = Math.floor((winHeight * (1-Tborder)) / 3); var BoxWidth = BoxHeight; var howmanyx = Math.floor(winWidth / BoxWidth) + 1; var howmanyy = 3; var HowMany = howmanyx * howmanyy; var used = new Array(howmanyIMG); var CMYG = ["00AEEF","EC008C","FFF200","41AD49"] function RNDy(numby){ return Math.floor(Math.random()*numby); } function getUniq(){ /* alert("run getuniq");*/ var n; while ( used[ n = RNDy(howmanyIMG) ] ){} used[ n ] = true; return n; } function ColorRND() { if (RNDy(4) ==1) { return true; }else{ return false; } } function PlacePop (HMx,HMy){ var counter = 0; var countc = 0; for(x=0;x<=HMx;x++){ var countr = 0; for(y=0;y<HMy;y++){ var divy = document.createElement("div"); var divyID = 'box' + counter; divy.setAttribute('id', divyID) divy.style.position="absolute"; divy.style.zIndex = counter + 3; divy.style.visibility = 'visible'; divy.style.borderWidth = '1'; divy.style.borderColor = '#000000'; divy.style.pixelLeft= x * BoxWidth + (2 * countc); divy.style.pixelTop= y * BoxHeight + (winHeight * Tborder) + (2 * countr); divy.style.pixelWidth= BoxWidth; divy.style.pixelHeight= BoxHeight; if (ColorRND()){ /*divy.innerHTML = 'color';*/ divy.style.backgroundColor = "#" + CMYG[RNDy(4)]; }else{ /*divy.innerHTML = 'image';*/ divy.style.backgroundImage = "url(resourses/images/portfolio/" + getUniq() + ".png)"; divy.style.backgroundPosition = "center"; /*RNDy(100) + "% " + RNDy(100) + "%";*/ } document.body.appendChild(divy); counter++; countr++; }countc++; } /* alert("ran" + counter + " times");*/ } /* used = null;*/ </script> THANKS FOR ANY HELP YOU CAN GIVE! Hey Guys! I've previously done HTML, but now started to learn some aspects of Javascript but getting rather confused with Loops! I've done a some coding for the Loop question (probably doesn't make sense) but I was wondering if you could help me out? I'm about as confused as a cow on a Astro Turf so my code may look terrible! - For this question you will: Draw a flow chart and write a javascript function which will use a for loop and allow the user to enter the details for four students when the program is run and display the average. Assume that they equal weighting. Hint: Javascript may assume that the value received from a prompt is a string so use parseInt() to make sure the number is an integer. Here is my code: (I'm using Aptana) Code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <meta http-equiv="Content-Type" content="text/javascript; charset=utf-8"/> <title>Average Marks</title> <!-- Date: 2011-10-27 --> <head> <script type="text/javascript"> function marks () { var mark1 = 10; var mark2 = 25; var mark3 = 50; for(var mark1 = 10; mark1<20; mark1++) (var mark2 = 25; mark2<50; mark2++) (var mark3 = 50; mark3<90; mark3++) { alert(mark1 + "<br /> "); (mark2 + "<br /> "); (mark3 + "<br />" ); console.log(mark1) console.log(mark2) console.log(mark3) } } function average () { parseInt() } </script> <body onload="marks()"> </body> </head> </html> P.S. I'm not using the prompt for the user to enter their details yet, as I wanted to test it with the marks already set. Regards Hello, i am new here however my knowledge is not that limited like that one guy wolf who oldMaster was helping with i read the RULES and his thread lol so my question is, i have made a for loop and in side the for loop i wrote document.write(<td>date</td>"<td class = 'amt'>amount</td>); where date, amount, firstName, and lastName, are the values of the date, amount, firstName, and lastName arrays for the index indicated by the current value of the for loop counter varible so questions : i have spent the past 3 days looking online for the correct answer document.write(<td>date</td>"<td class = 'amt'>amount</td>); ? HTML FILE Code: <title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> <script type = "text/javascript" src = "list.js"></script> <!-- caling the external file --> <script type ="text/javascript"> function amountTotal(){ //i dont think we need an array made because we have called the external file called list.js which holds the arrays //sets the variable to 0 var total = 0; //new Array("firstName", "lastName", "street", "city", "state", "zip", "amount", "date"); //that loops through all the values in the amount array, at each point in the loop add the current value of the array item to the value of the total variable for(var i = 0; i < amount.length; i++) { total = total + amount[i]; }//enf forloop //i must return the sum of all the values in the amount array return total; }//end of function total </script> </head> <body> <div id="title"> <img src="logo.jpg" alt="The Lighthouse" /> The Lighthouse<br /> 543 Oak Street<br /> Owensboro, KY 42302<br/> (270) 555-7511 </div> <div id="data_list"> <!--//creates a new script --> <script type = "text/javascript"> document.write("<table border='1' rules='rows' cellspacing='0'>"); document.write("<tr>"); document.write("<th>Date</th><th>Amount</th><th>First Name</th>"); document.write("<th>Last Name</th><th>Address</th>"); document.write("</tr>"); document.write("</table>"); for(var i = 0; i < date.length; i++) { if(i % 2 ) document.write("<tr>"); else document.write("<tr class='yellowrow'>"); document.write("<td>"date"</td>"<td class = 'amt'>amount"</td>"); }//end for </script> </div> <div id="totals"> <!--//this creates a script --> <script type = "text/javascript"> //this is how to print a table to the screen only when html is inside a script document.write( <table border='1' cellspacing='1'> <tr> <th id ='sumTitle' colspan='2'> Summary </th> </tr> <tr> <th>Contributors</th> <th>contributions</th> </tr> <tr> <th>Amount</th> <td>$total</td> </tr> </table>); </script> </div> </body> </html> THIS IS THE ARRAY LIST WHICH IS THE EXTERNAL FILE Code: firstName = new Array(); lastName = new Array(); street = new Array(); city = new Array(); state= new Array(); zip = new Array(); amount = new Array(); date = new Array() firstName[0]="Nina"; lastName[0]="Largent"; street[0]="88 Regal Lane"; city[0]="Williamsburg"; state[0]="KY"; zip[0]="40769"; amount[0]=125; date[0]="2011-09-18"; firstName[1]="Mike"; lastName[1]="Hunt"; street[1]="Da404 Barrow Street"; city[1]="London"; state[1]="KY"; zip[1]="40742"; amount[1]=75; date[1]="2011-09-18"; firstName[2]="Monica"; lastName[2]="Lang"; street[2]="743 Stawlings Drive"; city[2]="Danville"; state[2]="KY"; zip[2]="40423"; amount[2]=50; date[2]="2011-09-16"; firstName[3]="William"; lastName[3]="Mcknight"; street[3]="102 Maple Lane"; city[3]="Danville"; state[3]="KY"; zip[3]="40423"; amount[3]=150; date[3]="2011-09-15"; firstName[4]="Latrina"; lastName[4]="Hults"; street[4]="750 Whitehall Road"; city[4]="London"; state[4]="KY"; zip[4]="40742"; amount[4]=250; date[4]="2011-09-14"; firstName[5]="Danny"; lastName[5]="Shamblin"; street[5]="123 Smith Drive"; city[5]="Owensboro"; state[5]="KY"; zip[5]="42303"; amount[5]=50; date[5]="2011-09-13"; firstName[6]="Tina"; lastName[6]="Ammons"; street[6]="888 Evans Way"; city[6]="Williamsburg"; state[6]="KY"; zip[6]="40769"; amount[6]=50; date[6]="2011-09-13"; firstName[7]="Joanne"; lastName[7]="Fine"; street[7]="210 Bowling Terrace"; city[7]="Williamsburg"; state[7]="KY"; zip[7]="40769"; amount[7]=125; date[7]="2011-09-11"; firstName[8]="Charlotte"; lastName[8]="Foulk"; street[8]="109 South Road"; city[8]="Danville"; state[8]="KY"; zip[8]="40423"; amount[8]=50; date[8]="2011-09-10"; firstName[9]="Candice"; lastName[9]="Alfaro"; street[9]="108 Atwood Avenue"; city[9]="Owensboro"; state[9]="KY"; zip[9]="42303"; amount[9]=400; date[9]="2011-09-08"; firstName[10]="Kristi"; lastName[10]="Laine"; street[10]="512 North Lane"; city[10]="Williamsburg"; state[10]="KY"; zip[10]="40769"; amount[10]=225; date[10]="2011-09-08"; firstName[11]="Elisabeth"; lastName[11]="Carbone"; street[11]="381 Main Street"; city[11]="London"; state[11]="KY"; zip[11]="40742"; amount[11]=200; date[11]="2011-09-07"; firstName[12]="James"; lastName[12]="Larsen"; street[12]="212 Rawlings Way"; city[12]="Jackson"; state[12]="KY"; zip[12]="41339"; amount[12]=125; date[12]="2011-09-07"; firstName[13]="Ralph"; lastName[13]="Thornton"; street[13]="444 Smith Drive"; city[13]="Owensboro"; state[13]="KY"; zip[13]="42303"; amount[13]=100; date[13]="2011-09-07"; firstName[14]="Robin"; lastName[14]="Witt"; street[14]="78 Norland Pines"; city[14]="London"; state[14]="KY"; zip[14]="40742"; amount[14]=75; date[14]="2011-09-07"; firstName[15]="Alex"; lastName[15]="Ruiz"; street[15]="102 Sunset Road"; city[15]="Jackson"; state[15]="KY"; zip[15]="41339"; amount[15]=50; date[15]="2011-09-06"; firstName[16]="Callie"; lastName[16]="Rudy"; street[16]="3 Sunset Road"; city[16]="Jackson"; state[16]="KY"; zip[16]="41339"; amount[16]=50; date[16]="2011-09-06"; firstName[17]="Michael"; lastName[17]="Harrell"; street[17]="125 Sunset Road"; city[17]="Jackson"; state[17]="KY"; zip[17]="41339"; amount[17]=50; date[17]="2011-09-06"; firstName[18]="Edgar"; lastName[18]="Morales"; street[18]="387 North Lane"; city[18]="Williamsburg"; state[18]="KY"; zip[18]="40769"; amount[18]=250; date[18]="2011-09-05"; firstName[19]="Arlene"; lastName[19]="Lutz"; street[19]="7888 Clear View Drive"; city[19]="Danville"; state[19]="KY"; zip[19]="40423"; amount[19]=75; date[19]="2011-09-05"; firstName[20]="Earl"; lastName[20]="Holmes"; street[20]="1001 Rawlings Way"; city[20]="Jackson"; state[20]="KY"; zip[20]="41339"; amount[20]=500; date[20]="2011-09-04"; firstName[21]="Bernice"; lastName[21]="Drew"; street[21]="25 Main Street"; city[21]="London"; state[21]="KY"; zip[21]="40742"; amount[21]=150; date[21]="2011-09-04"; firstName[22]="Patrick"; lastName[22]="Granier"; street[22]="100 Atwood Avenue"; city[22]="Owensboro"; state[22]="KY"; zip[22]="42303"; amount[22]=75; date[22]="2011-09-03"; firstName[23]="Henry"; lastName[23]="Bailey"; street[23]="37 East Maple Street"; city[23]="Danville"; state[23]="KY"; zip[23]="40423"; amount[23]=50; date[23]="2011-09-03"; firstName[24]="Ginny"; lastName[24]="Rainey"; street[24]="657 Dawson Lane"; city[24]="Danville"; state[24]="KY"; zip[24]="40423"; amount[24]=50; date[24]="2011-09-03"; firstName[25]="Ginny"; lastName[25]="Rainey"; street[25]="657 Dawson Lane"; city[25]="Danville"; state[25]="KY"; zip[25]="40423"; amount[25]=75; date[25]="2011-09-03"; firstName[26]="Basilia"; lastName[26]="Lu"; street[26]="851 Flad Court"; city[26]="Jackson"; state[26]="KY"; zip[26]="41339"; amount[26]=500; date[26]="2011-09-02"; firstName[27]="Livia"; lastName[27]="Mckinnon"; street[27]="557 Ivy Avenue"; city[27]="Jackson"; state[27]="KY"; zip[27]="41339"; amount[27]=50; date[27]="2011-08-31"; firstName[28]="Kris"; lastName[28]="Levesque"; street[28]="542 Upton Avenue"; city[28]="Owensboro"; state[28]="KY"; zip[28]="42303"; amount[28]=100; date[28]="2011-08-31"; firstName[29]="Lynwood"; lastName[29]="Ingersoll"; street[29]="723 Jackson Avenue"; city[29]="Owensboro"; state[29]="KY"; zip[29]="42303"; amount[29]=500; date[29]="2011-08-30"; firstName[30]="Petronila"; lastName[30]="Damico"; street[30]="44 Stewart Street"; city[30]="London"; state[30]="KY"; zip[30]="40742"; amount[30]=250; date[30]="2011-08-30"; firstName[31]="Hugh"; lastName[31]="Warren"; street[31]="585 Lindon Court"; city[31]="Williamsburg"; state[31]="KY"; zip[31]="40769"; amount[31]=50; date[31]="2011-08-28"; firstName[32]="Tom"; lastName[32]="Thomas"; street[32]="Rigel Avenue"; city[32]="London"; state[32]="KY"; zip[32]="40742"; amount[32]=100; date[32]="2011-08-27"; firstName[33]="Steve"; lastName[33]="Bones"; street[33]="900 Lawton Street"; city[33]="Williamsburg"; state[33]="KY"; zip[33]="40769"; amount[33]=50; date[33]="2011-08-25"; firstName[34]="Jeri"; lastName[34]="White"; street[34]="Hawkes Lane"; city[34]="Owensboro"; state[34]="KY"; zip[34]="42303"; amount[34]=150; date[34]="2011-08-25"; Hi everyone. I have a loop question. This is my assignment for my Comp Apps class. The whole thing is a store selling guitar picks. What I'm missing now is a loop. After the costumer places the order, he has the choice to go back and buy more or complete the order. In the end all the order the costumer placed adds up to the total. This is what I have so far: PHP Code: <script type="text/javascript"> var name = prompt("Welcome to Pick Center. Please enter your name", " "); alert("Hello " + name + "! Please look through our list of picks before placing your order."); var product = prompt("What would you like to buy?", ""); var quantity = prompt("How many " + product + " would you like to order?", ""); var confirming = confirm(""+ name + " you ordered " + quantity +" " + product +" picks. Is this correct?"); var price = " "; var item_discount = " "; if ( confirming == true ) { } else { alert("Refresh the page to reload and place a new order.")} if ( product == "dirtbag" ) { price = "5"; item_discount = "0.3";} else if ( product == "delrin" ) { price = "7"; item_discount = "0.2";} else if ( product == "speedpick" ) { price = "10"; item_discount = "0.5";} else if ( product == "stubby") { price = "25"; item_discount = "0.25";} else { alert("Sorry," + name + ". You entered an invalid product. Refresh the page to reload and place the order again.");} var cost_of_order = price * quantity; var discount = price * item_discount * quantity; var total = cost_of_order - discount; document.write("<br><h1> Your Order: </h1></br><br>"); document.write("Thank you for placing an order with us, <b>" + name + "</b>.<br><br>"); document.write("The cost of buying " + quantity + " " + product + " picks is <b>$" + cost_of_order + "</b>.<br><br>"); document.write("The discount for this purchase is <b>$" + discount + "</b>.<br><br>"); document.write("With discount, your total order cost is <b>$" + total + "</b>.<br><br>"); </script> I've tried reading around and I bought a couple of books but I just can't get a grasp on loops. Can someone please help me with this? Hey Guys, I'm currently a seasoned programmer who is in a programming class at my school. We're currently learning advanced JavaScript, and we're on the topic of nested loops. After teaching us about for and while loops, my teacher gave us a little puzzle to solve. It's kind of difficult to explain, but I'll give you guys my current code and what it outputs. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Word Reversal</title> <script type="text/javascript"> var ask = prompt("How many words do you want?",""); while (ask < "1") { alert("You have to have at least one word!"); var ask = prompt("How many words do you want?",""); } var num = parseInt(ask) + 1; var final = ""; for (var i=1; i < num; i++) { var word = prompt("What's word " + i + "?"); final = final + "Word " + i +": " + word + "<br/>"; } </script> </head> <body> <script type="text/javascript"> document.writeln(final); </script> </body> </html> The current output, when the user wants two words, and word 1 is one and word 2 is two, comes out to be: Code: Word 1: one Word 2: two Which is great, but the only problem is, this is what the output's supposed to be: Code: Word 2: two Word 1: one I'm stumped. I've had numerous programming challenges in my life which I've solved, but I'm not sure where to go next on this one. The script is supposed to use a nested loop, but what goes in what loop to reverse the order of the user's input? I asked my teacher for help, but he told me "Ask someone else." I asked another seasoned programmer in my class, who was just about as stumped as I was, so I went back to my teacher. "Well, ask another person" he replied. And can you believe this guy has a Master's Degree of Computer Science? So I'm asking you guys: the community. I hope someone will be able to help me. On top of that, I have to help and tutor two special education students in my class on this kind of stuff during class, and they can't get the project done until I get it done, as they learn from analyzing and copying my work (which my teacher told me to do). They get upset when they have nothing to code, and they end up goofing off the entire period, or using it as a study hall. I need to get them back on track, so we can move on to the next project. Please help me with this code - it would be greatly appreciated. Thank you! Hello codingforums.com! Right, this is probably going but such a stupid newbie thread but here goes.. I've finally got myself into gear to start learning javascript. I've been watching video tutorials, learning from websites and simply learning by error. I understand the concept of for loops, but the whole nested thing doesn't seem to click for some reason. I thought i understood and managed to write a piece of code that constantly writes '*' across the screen. Could someone with some pretty damn good knowledge of javascript be able to walk me through step by step of my script to explain what actually is happening? It would help loads. here is the script, many thanks!! <script type="text/javascript"> var counter = 0; function writeStars(){ for(i=0;i<1;i++){ for(a=0;a<=counter;a++){ document.write("*"); } counter++ document.write("<br />"); } } setInterval("writeStars()", 200); </script> I am working on making 2 for loops of 2 arrays to get the total of them. Then I need to get the average heights. This is for a test, yet I have not got a clue, so I need clues as I cant get it to work and I am a new coder to javascript. Code: var heights = [15,16,17,18,19]; var numbers = [2,1,6,4,2]; var average = new Array(5); average = 0 for (var heights = 0; heights <= 5; heights = heights+ 1) { total = 0 } for (var numbers = 0; numbers <= 5; numbers = numbers + 1) { total = 0 average = heights / numbers; } document.write('The average height is ' + average); Am I on the right road? I need to use this format and not functions. I have got 2 for statements but maybe I could do this with one, it is so tricky this javascript. I created a For Loop and counter starts at 0, then increase in increments of 1 after each iteration of loop i run a command 1( add html code such as Code: <td>named (part)</td> <td class= 'num'>votes</td> Then create variable of named percent use totalV for value of sum parameter then i add html code of Code: <td class='num'>(percent%(</td> then i add a function named createBar(0 using race[0], name1, party1, and votes1 in parameter values this is my coding Code: for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("<td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> </head> so any improvements or what i am missing in my functions. |