JavaScript - For...in Loop Failing, Calling Only Last Array Element
I'm hoping someone can help correct a small problem with this script, which is intended to highlight particular text strings.
Background: The script is being used at a MediaWiki site, and is adapted from a working script from Wikipedia (highlightmyname.js). The original script highlights the logged-in user's username (represented by wgUserName). I've made a copy of the script, which you can see in full here, and adapted it to work on a pre-defined array of names, adding: Code: var Admin; var ArrayAdmins = ['Adam', 'Axiomist', 'Matt', 'Steve']; for (Admin in ArrayAdmins) I also replaced each instance of wgUserName with ArrayAdmins[Admin] The problem: is that, instead of highlighting all instances of every element in ArrayAdmins, only the last element listed ('Steve') is being used. So my question is, what change(s) need to be made to apply function highlightmyname to every element in ArrayAdmins? Any help would be hugely appreciated! Similar TutorialsOk, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. Hello Pros. I am having a problem with getting id of the active element which calls function savePanelPosition(), as a result, I cannot get a new location of this element and pass it to my Page Method SaveCoords() All draggable panels are created dynamically in code-behind. Please, see the javascript code below. Any ideas/help are greatly appreciated function pageLoad() { var Max = "<%=qtyMax%>"; for (i = 0; i < Max; i++) { $find('DragP' + i).add_move(savePanelPosition); } } function savePanelPosition() { var elem = document.activeElement; var loc = $common.getLocation(elem); PageMethods.SaveCoords(elem, loc.x, loc.y); /* there is a call to PageMethods.SaveCoords(), but elem = objectHTMLBodyElement, loc.x=0, loc.y =0 */ } I've been running into some trouble with a script that just isn't working, and since I'm not encountering any error messages and a similar script on the same page is working just fine, I'm really puzzled. Anyways, here's the code I'm having trouble with: Code: function ShowHide(Numb){ Ident1 = AdIDList[Numb]+"Tx"; Ident2 = AdIDList[Numb]+"Lnk"; if (AdLink[Numb] == "hidden"){ document.getElementById(Ident1).style.height = "355px"; AdLink[Numb] = "visible"; } if (AdLink[Numb] =="visible"){ document.getElementById(Ident1).style.height = "55px"; AdLink[Numb] = "hidden"; } } And here's the page code calling it (The page is assembled via PHP from a database, but I'm grabbing the code from my browser) Code: <a href="#Good ShepherdLnk" id="Good ShepherdLnk" onclick="ShowHide(2);return false;" class="AdLink">Stories</a><br> And, here's a similar bit of code on the same page that is working just as it's supposed to. Code: function hideimage(){ for (Count=0; Count<AdTotal; Count ++){ if (VisPic[Count]=="visible"){ Ident = AdIDList[Count]+"AdB"; document.getElementById(Ident).style.visibility = "hidden"; VisPic[Count]="hidden"; } } } function bigimage(Item){ hideimage(); Ident1 = AdIDList[Item]+"AdB"; document.getElementById(Ident1).style.left="35%"; document.getElementById(Ident1).style.visibility = "visible"; VisPic[Item] = "visible"; } 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>Untitled Document</title> <style type="text/css"> #status { background-color:#FF0; width: 300px; height: 150px; overflow:scroll; margin-top: 25px; } #money { position:absolute; left: 325px; top: 416px; } </style> <script type="text/javascript"> function Machine() { this.getCash = function() { var i = 0; var rand = 0; while (i < 2) { t = setTimeout("rand = Math.ceil(Math.random() * 4 )", 1000); alert(rand); i++; } clearTimeout(t); } } var soda = new Machine(); soda.getCash(); </script> </head> <body> <div style="margin-bottom:25px"> Soda Machine. <p>_________________</p> 1. Earn Money <br /> 2. Buy Soda </div> <table> <thead> <th>Soda</th> <th>Price</th> <th>Buy</th> </thead> <tbody> <tr> <td> Basic Fizz </td> <td> $5 </td> <td> <input type="button" id="b_fizz" value="Buy Basic Fizz" /> </td> </tr> <tr> <td> Advanced Fizz </td> <td> $11 </td> <td> <input type="button" id="a_fizz" value="Buy Advanced Fizz" /> </td> </tr> <tr> <td> The Good Stuff </td> <td> $17 </td> <td> <input type="button" id="cc_fizz" value="Buy Coca Cola" /> </td> </tr> </tbody> </table> <div id="status"> <p style="margin-top:0">Status Window: </p> </div> <input type="text" id="money" value="$0" disabled="disabled" /> <input type="button" id="earn" value="Earn Cash" /> </body> </html> Basically, what I'm trying to do is get a random number every second for 2 seconds automatically so that in the status window it says: "You earned $2" "You earned $3" ....etc. But my random number keeps showing up as 0. I know I'm probably overlooking something as far as closures...can someone please enlighten me? Check the javascript code tried this also..same result for everything I try: D: Code: function Machine() { this.rand = 0; this.r = function() { this.rand = Math.ceil(Math.random() * 4); } this.getCash = function() { var i = 0; while (i < 3) { t = setTimeout("this.r()", 1000); alert(this.rand); i++; } clearTimeout(t); } } var soda = new Machine(); soda.getCash(); Hi Everyone, I am not able to figure out why the function "changeDiv(the_div,the_change)" is not called from the for loop in the function displayUsers(keeper)that I generated. The displayUsers is written to get rid of excess code in the function display(keeper). Can someone, please point out what the mistake is? Code: function changeDiv(the_div,the_change) { var the_style = getStyleObject(the_div); if (the_style != false) { the_style.display = the_change; } } function getStyleObject(objectId) { if (document.getElementById && document.getElementById(objectId)) { return document.getElementById(objectId).style; } else if (document.all && document.all(objectId)) { return document.all(objectId).style; } else { return false; } } //Shows input information for # of users selected function displayUsers(keeper) { var display=keeper; var i,user; for(i=1;i<= display;i++) { user="user"+i; changeDiv('user','block'); } } /*function display(keeper) { if (keeper == 1) { changeDiv('user1', 'block'); changeDiv('user2', 'none'); changeDiv('user3', 'none'); changeDiv('user4', 'none'); changeDiv('user5', 'none'); changeDiv('user6', 'none'); changeDiv('user7', 'none'); changeDiv('user8', 'none'); changeDiv('user9', 'none'); changeDiv('user10','none'); } else if (keeper == 2) ... ... ... else { changeDiv('user1', 'none'); changeDiv('user2', 'none'); changeDiv('user3', 'none'); changeDiv('user4', 'none'); changeDiv('user5', 'none'); changeDiv('user6', 'none'); changeDiv('user7', 'none'); changeDiv('user8', 'none'); changeDiv('user9', 'none'); changeDiv('user10','none'); } }// end function display(keeper)*/ Hi, I'm trying to update an element on my page after every iteration of a loop. I'm using a simple innerHTML to achieve this, however, what happens is the page freezes during the entirety of the loop, and finally updates when the loop finishes. PHP Code: // below function is triggered by clicking some element function go() { for (var i = 1; i < len; ++i) { document.getElementById("output").innerHTML += "Processing #" + i; doStuff(); } } Ideally, I'd like the output to update and scroll down as the function processes the data. Is the problem that innerHTML can't keep up with the speed at which the for loop progresses? i have tried searching the forums for help but really am getting no where. i am trying to call an array item from an input box. the input is all numbers. the arrays are v + numbers. i cannot seem to figure out how to get the item from the array. eg Code: var v00501 = ["HOLTSVILLE,I R S SERVICE CENTER","NY","631","-5","Y"] var v00544 = ["HOLTSVILLE,IRS SERVICE CENTER","NY","631","-5","Y"] var v00601 = ["ADJUNTAS,JARD DE ADJUNTAS,URB SAN JOAQUIN","PR","787/939","-4","N"] function pop() { var zipv = "v" + myform.Zip.value +"[0]"; alert(zipv); } or Code: function pop() { alert(pop1()); } function pop1() { return "v" + myform.Zip.value +"[0]"; } so for this if the user typed in 00501 i get v00501[0] no matter what i try. i want HOLTSVILLE,I R S SERVICE CENTER to be returned or whatever item i am calling for. this all has to be on client side as i dont have server access so the zip codes are all set up as arrays in a seperate file. i really dont know alot about javascript but i am learning. any help on how i can accomplish this would be appreciated. Im trying to add to each element within an array. In this program I have an existing array which is called aScores. I have copied its contents into another array called aScores using slice. Now Im trying to add the value of variable called classCurve to each element of aCurve using a for loop (see under the Curve Scores functrion section). However, it does not seem to add the two together(e.g 78 + 5). Any advice would be very helpful. Here is my code: Code: <?xml version="1.0" encoding="UTF-8"?> <!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> <title></title> <script> <!-- var aScores = new Array(); //array to hold test scores var aCurve = new Array(); //array to hold test scores with curve var classAveRounded = 0; //average of test scores var howLong = 0; //length of array -- contingent on how many test scores entered //------------------- LoadScores function ----------------------------- function LoadScores() { var classAve = 0; var rawScores = document.getElementById("Scores").value; aScores=rawScores.split(","); //seperate the test scores by comma //alert(aScores[1]); //test to see if they are separated var howLong = aScores.length; //variable to measure how long the array is for(i=0; i<howLong; i++){ aScores[i] = parseInt(aScores[i]); //convert strings to numbers } //alert(aScores[0] + aScores[1]); //test to make sure array contains numbers aScores.sort(sortNumber); //sort the scores from highest to lowest //insert scores from the array into the score text boxes. for (i=0; i<howLong; i++) { document.getElementById("Score" + i).value = aScores[i]; } //total the test scores var total=0; for(i=0; i<howLong; i++) { total += aScores[i]; } //average the total and insert it into the Average textbox(Math.ceil rounds up aveCalc). classAve = total/howLong; classAveRounded = Math.ceil(classAve); document.getElementById("Average").value = classAveRounded; } //------------------- sortNumber function ------------------------------ function sortNumber(a,b){ return b-a; } //------------------- CurveScores function ----------------------------- function CurveScores() { var classCurve = 0; alert(classAveRounded); if(classAveRounded<75) { classCurve=(75-classAveRounded); }else{ classCurve=0; } alert(classCurve); aCurve=aScores.slice(); //alert(aCurve[7]); //test to see if aCurve holds test scores for(i=0; i<howLong; i++) { aCurve[i]=aCurve[i] + classCurve; } // alert(aCurve[0]); //total the curved scores var totalCurvedScores=0; for(i=0; i<howLong; i++) { totalCurvedScores += aCurve[i]; } //average the total and insert it into the CurvedAverage textbox(Math.ceil rounds up aveCalc). curvedAve = totalCurvedScores/howLong; curvedAveRounded = Math.ceil(curvedAve); document.getElementById("CurvedAverage").value = curvedAveRounded; } --> </script> </head> <body> <table border="1"> <tr style="background-color:#F0F0F0; font-size:10pt; font-weight:bold; text-align:center; vertical-align:bottom"> <td>Score</td> <td>Curved</td> <td>Grade</td> </tr> <tr> <td> <input id="Score0" type="text" style="width:60px;text-align:right"/><br/> <input id="Score1" type="text" style="width:60px;text-align:right"/><br/> <input id="Score2" type="text" style="width:60px;text-align:right"/><br/> <input id="Score3" type="text" style="width:60px;text-align:right"/><br/> <input id="Score4" type="text" style="width:60px;text-align:right"/><br/> <input id="Score5" type="text" style="width:60px;text-align:right"/><br/> <input id="Score6" type="text" style="width:60px;text-align:right"/><br/> <input id="Score7" type="text" style="width:60px;text-align:right"/><br/> <input id="Score8" type="text" style="width:60px;text-align:right"/><br/> <input id="Score9" type="text" style="width:60px;text-align:right"/><br/> </td> <td> <input id="CurvedScore0" type="text" style="width:60px;text-align:right"/><br/> <input id="CurvedScore1" type="text" style="width:60px;text-align:right"/><br/> <input id="CurvedScore2" type="text" style="width:60px;text-align:right"/><br/> <input id="CurvedScore3" type="text" style="width:60px;text-align:right"/><br/> <input id="CurvedScore4" type="text" style="width:60px;text-align:right"/><br/> <input id="CurvedScore5" type="text" style="width:60px;text-align:right"/><br/> <input id="CurvedScore6" type="text" style="width:60px;text-align:right"/><br/> <input id="CurvedScore7" type="text" style="width:60px;text-align:right"/><br/> <input id="CurvedScore8" type="text" style="width:60px;text-align:right"/><br/> <input id="CurvedScore9" type="text" style="width:60px;text-align:right"/><br/> </td> <td> <input id="Grade0" type="text" style="width:60px;text-align:center"/><br/> <input id="Grade1" type="text" style="width:60px;text-align:center"/><br/> <input id="Grade2" type="text" style="width:60px;text-align:center"/><br/> <input id="Grade3" type="text" style="width:60px;text-align:center"/><br/> <input id="Grade4" type="text" style="width:60px;text-align:center"/><br/> <input id="Grade5" type="text" style="width:60px;text-align:center"/><br/> <input id="Grade6" type="text" style="width:60px;text-align:center"/><br/> <input id="Grade7" type="text" style="width:60px;text-align:center"/><br/> <input id="Grade8" type="text" style="width:60px;text-align:center"/><br/> <input id="Grade9" type="text" style="width:60px;text-align:center"/><br/> </td> </tr> <tr> <td><input id="Average" type="text" style="width:60px;text-align:right"/></td> <td><input id="CurvedAverage" type="text" style="width:60px;text-align:right"/></td> <td> </td> </tr> <tr> <td><input type="button" value="Load" style="width:60px;font-size:7pt" onclick="LoadScores()"/></td> <td><input type="button" value="Curve" style="width:60px;font-size:7pt" onclick="CurveScores()"/></td> <td><input type="button" value="Grades" style="width:60px;font-size:7pt" onclick="AssignGrades()"/></td> </tr> </table> <div style="position:relative; left:225px; top:-25px; font-size:10pt"> <b>Enter Scores: </b> <input id="Scores" type="text" style="width:250px; font-family:courier new" value="40,46,48,56,62,64,66,70,76,78"/> </div> </body> </html> What I need help with is sorting the [0] of my array. I need it to sort so that if the user puts in his last name, whether its uppercase or lowercase (Adams, adams), it will sort through the list of students I add, and put them in an alphabetic order i.e adams, Adams, cook, Douglas....and so on. Here is the code that I have below for just sorting by last name, which will seperate the lowercase entries from the uppercase entries. That would be the opposite of what I want. I had it sorted so that it would sort the [o], which is where the last name value is located. Any thoughtful help would be appreciated. Code: function Last_names( s1, s2 ) { if ( s1[0] > s2[0] ) return 1; return 0; } function sortLast(form) { StudentsLists.sort( Last_names ); windows(form);//calling the windows function each time the sortLast function is called } --------RESOLVED-------- I am trying to make a finance tracker, but for some reason this code will only output the first transaction: Code: <html> <head> <style> tr:nth-child(even) {background: #CCC} tr:nth-child(odd) {background: #FFF} </style> <script type="text/javascript"> var finance={ ls : localStorage, codes : new Array(), getCodes : function (){ finance.codes=(eval("["+finance.ls.code+"]")) return finance.codes; }, dates : new Array(), getDates : function (){ finance.dates=(eval("["+finance.ls.dates+"]")) return finance.dates; }, desc : new Array(), getDescs : function (){ finance.desc=(eval("["+finance.ls.desc+"]")) return finance.desc; }, change : new Array(), getChanges : function (){ finance.change=(eval("["+finance.ls.change+"]")) return finance.change; }, getAll : function(){ var t=new Array(); t[0]=finance.getCodes(); t[1]=finance.getDates(); t[2]=finance.getDescs(); t[3]=finance.getChanges(); return t; }, getRows : function(){ var temp=new Array(); var bal=0; for (i=0;i<finance.getAll()[0].length;i++){ bal+=finance.getAll()[3][i]; var temp3=document.createElement("tr"); var temp4=new Array(); for(a=0;a<6;a++){ temp4[a]=(document.createElement("td")) } temp4[0].innerHTML=finance.getAll()[0][i]; temp4[1].innerHTML=finance.getAll()[1][i]; temp4[2].innerHTML=finance.getAll()[2][i]; temp4[3].innerHTML=((finance.getAll()[3][i]>0)?"":finance.getAll()[3][i]); temp4[4].innerHTML=((finance.getAll()[3][i]<0)?"":finance.getAll()[3][i]); temp4[5].innerHTML=bal; for(i=0;i<6;i++){ temp3.appendChild(temp4[i]); } temp.push(temp3); } for(i=0;i<temp.length;i++){ document.getElementById("fin").appendChild(temp[i]); } } } localStorage.code='" ","1001","DC"'; localStorage.dates='" ","8/30/2010","9/4/2010"'; localStorage.desc='"Starting","Check for Bob","ATM"'; localStorage.change='100,-10,-20'; </script> </head> <body onload="finance.getRows();"> <table id="fin"> <tr><th>Code</th><th>Date</th><th>Description</th><th>Payment</th><th>Deposit</th><th>Balance</th></tr> </table> </body> </html> hahahahaha wow im dumb i forgot that nesting two for statements that use "i" is a nono also i know the code may be sloppy, i am just building it now, i will clean it up later. Hi. I'm fairly new to javascript. I have a code where I'm trying to generate scrollx1 through scrollx100. I can get the array to work with doc.write and I can get one concat variable to work in the element but when I combine them it doesn't work. Any suggestions as to what I need to add to this code: var sp=1; for (sp=1;sp<=100;sp++) { var sx = "scrollx"; var sy = "scrolly"; var thissx = sx + sp; var thissy = sy + sp; theForm[thissx].value = scrollx; theForm[thissy].value = scrolly; } Any help would be much appreciated!! Hi. I'm fairly new to javascript. I have a code where I'm trying to generate scrollx1 through scrollx100. I can get the array to work with doc.write and I can get one concat variable to work in the element but when I combine them it doesn't work. Any suggestions as to what I need to add to this code: Code: var sp=1; for (sp=1;sp<=100;sp++) { var sx = "scrollx"; var sy = "scrolly"; var thissx = sx + sp; var thissy = sy + sp; theForm[thissx].value = scrollx; theForm[thissy].value = scrolly; } Any help would be much appreciated!! Hi all. I am having a problem understanding exactly how setInterval and setTimeout work and really need some help. I want to create an array and then print out each element one at a time at one second intervals. I've only been able to come up with something like this, but it just prints the last value of the array after a second. Code: <script type = "text/javascript"> <!-- var myArray = new Array(); for (var i = 0; i < 11; i++){ myArray[i]=i+50; } for (var i = 0; i < myArray.length-1; i++){ setInterval("document.getElementById('here').innerHTML = myArray[i];", 1000); } //--> </script> <div id="here">Stuff here</div> I want to create an array for a religious website that will display a different Bible verse for each day of the year. This is how I incremented each day of the year. Code: var myDate=new Date(); myDate.setFullYear(2011,2,4); myDate.setDate(myDate.getDate()+1); How do I make the connection between the array and the new date as it changes? This is a snippet from the array. Code: var dailyVerseRef=new Array(); dailyVerseRef[0]="Genesis 1:1"; dailyVerseRef[2]="Genesis 1:2"; dailyVerseRef[3]="Genesis 1:3"; dailyVerseRef[4]="Genesis 1:4"; dailyVerseRef[5]="Genesis 1:5"; dailyVerseRef[6]="Genesis 1:6"; dailyVerseRef[7]="Genesis 1:7"; dailyVerseRef[8]="Genesis 1:8"; I used a switch to go through the days of the week, but to go through the days of the year seems more difficult. Hi, Below is the code which is used to validate the entries on a form(some field are not be left blank). The user gets the msg when he hits the "Check"button. The problem is after the user gets the msg, I am not able to set the focus in the field which is the first element of an error array which stores the info about the fields with errors on this form. Please help. ========================================================== <html> <head> <script type="text/javascript"> function check_alert() { var errors=[]; if (text1.value==""||text1.value==null) { errors[errors.length]="Please enter the Company Name"; } if(text3.value==""||text3.value==null) { errors[errors.length]="Please enter the Address"; } if(text5.value==""||text5.value==null) { errors[errors.length]="Please enter the City"; } if(text6.value==""||text6.value==null) { errors[errors.length]="Please enter the Zip/Costal Code"; } if(text7.value==""||text7.value==null) { errors[errors.length]="Please enter the Country"; } if (errors.length>0) { reportErrors(errors); return false; } else return true; } function reportErrors(errors) { var msg="There are some errors..\n"; var numerror; for (var i=0;i<errors.length;i++) { numerror=i+1; msg+="\n"+numerror+"."+errors[i]; } alert(msg); document.form.element(errors[0]).focus(); } </script> </head> <body onload="text1.focus()"> Company:<input type="text" name="text1" /><br> Division:<input type="text" name="text2" /><br> Address1:<input type="text" name="text3" /><br> Address2:<input type="text" name="text4" /><br> City:<input type="text" name="text5" /><br> State:<select name="state"> <option value= "Alabama" selected>Alabama</option> <option value= "Alaska">Alaska</option> <option value= "Arizona">Arizona</option> <option value= "Arkansas">Arkansas</option> </select><br> Zip/Postal Code:<input type="text" name="text6"/><br> Country:<input type="text" name="text7" /><br> <input type="button" value="Check" onclick="return check_alert()"/> </body> </html> ======================================================= HI, I am new to JavaScript and need help with a code //names of couples stored in array var contestantNamesArray = ['Tom and Nazia', 'Pat and Dan', 'Sandra and Kofi', 'Ian and Adele', 'Paul and Costas']; //points awarded by judges and audience stored in arrays var judgesPointsArray = [2,1,5,4,3]; var audiencePointsArray = [4,5,2,3,1]; //Part (i)(a) //new array to store the combined points for each couple var combinedPointsArray = new Array (4); //Part (i)(b) //loop to add the judges and the audience points for each couple and to store them in the combined points array for (var score = 0; score < combinedPointsArray.length; score = score + 1) { combinedPointsArray[score] = judgesPointsArray[score] + audiencePointsArray[score]; } //Part(i)(c) //loop to find and write out the maximum number of points scored maxPointsScoredIndex = 0; for (var score = 1; score < combinedPointsArray.length; score = score + 1) { if (combinedPointsArray[score] > combinedPointsArray[maxPointsScoredIndex]) { maxPointsScoredIndex = score; } } document.write ('The maximum number of points was ' + combinedPointsArray[maxPointsScoredIndex] + '<BR>'); //Part (iii) //Add code that will // -- write out a heading for the list of couples scoring the maximum // -- write out the names of all the couples with the maximum number of combined points // keeping score of how many they are // -- at the end, write out whether a dance-off is required or not, depending on how many couples scored the maximum It's the third part that I'm struggling with. Could someone help me? Thank you! apparently this is supposed to be a loop... I got it off another topic here and it made NOOOO sense Code: //dandavis's ES5 Array methods: (function ArrayMethods(){var o=Array.prototype,it,i, e=eval('( {map:Z0,r=[];for(;i<m;i++){if(i in t){r[i]=a.call(b,t[i],i,t);}}return r;},filter:Z0,r=[],g=0;for(;i<m;i++){if(i in t&&a.call(b,t[i],i,t)){r[g++]=t[i];}}return r;},every:Z0;return m&&t.filter(a,b).length==m;},some:Z1;for(;m--;){if(m in t&&a.call(t,t[m],m,t)&&!--i){return true;}}return false;},lastIndexOf:Zb||-1;for(;m>i;m--){if(m in t&&t[m]===a){return l;}}return-1;},indexOf:Zb||0;for(;i<m;i++){if(i in t&&t[i]===a){return i;}}return-1;},reduce:Z0,r=b||t[i++];for(;i<m;i++){r=a.call(null,r,t[i],i,t);}return r;},reduceRight:Zm-1,r=b||t[i--];for(;i>-1;i--){r=a.call(null,r,t[i],i,t);}return r;},forEach:function(a,b){this.concat().map(a,b);return this;}})'.replace(/Z/g,"function(a,b){var t=this.concat(),m=t.length,i="));for(it in e){i=o[it];o[it]=i||e[it];} }());//end ArrayMethods() someone want to explain it to me? here is some more Code: (function(){var o=Array.prototype,it,i,e={ map:function(a,b){var t=this.concat(),m=t.length,i=0,r=[];for(;i<m;i++){if(i in t)r[i]=a.call(b,t[i],i,t)}return r}, filter:function(a,b){var t=this.concat(),m=t.length,i=0,r=[],g=0;for(;i<m;i++){if(i in t&&a.call(b,t[i],i,t)){r[g++]=t[i]}};return r}, every:function(a,b){var t=this.concat(),m=t.length,i=0;return m&&t.filter(a,b).length==m}, some:function(a,b){var t=this.concat(),m=t.length,i=1;for(;m--;){if(m in t&&a.call(t,t[m],m,t)&&!--i){return!0}}return!1}, lastIndexOf:function(a,b){var t=this.concat(),m=t.length,i=b||-1;for(;m>i;m--){if(m in t&&t[m]===a){return l}}return-1}, indexOf:function(a,b){var t=this.concat(),m=t.length,i=b||0;for(;i<m;i++){if(i in t&&t[i]===a){return i}}return-1}, reduce:function(a,b){var t=this.concat(),m=t.length,i=0,r=b||t[i++];for(;i<m;i++){r=a.call(null,r,t[i],i,t)}return r}, reduceRight:function(a,b){var t=this.concat(),m=t.length,i=m-1,r=b||t[i--];for(;i>-1;i--){r=a.call(null,r,t[i],i,t)}return r}, forEach:function(a,b){this.concat().map(a,b)} };for(it in e){i=o[it];o[it]=i||e[it]}}()); //end Array.16 injection it has something to do with eval... whats eval? sigh I hate arrays this is so confusing to try and read >< Hello, I have a homework assignment to complete and I don't understand 2 particular parts. I need to design a game that does the following: Based on assignment 3, write a program that allows you and the computer to take turns and guess each other's secret number (between 1 and 100); Requirements: * You and your opponent (computer) take turns to guess. * You and your opponent gives simple hints like in assignment 3 for each round. * Show how many rounds have passed. * Keep guessing record and display it to assist the game play. The guessing of the numbers needs to be simultaneous, and the professor wants us to use a while loop and an array. It is based on a previous assignment, in which we designed a program that would ask the user to guess a number between 1-100 that the computer generated. The user is prompted by alerts that say "too high" or "too low" and then is told when they guess correctly. This I understand, but I am confused about how to modify it to fit the new assignment. Here is the code I have: Code: <html> <head> <title> Homework #3 </title> <script type="text/javascript"> var randomNumber = Math.floor (Math.random()*100)+1; { var compNumber; var compNumber = Math.floor (Math.random()*100)+1; } { var copyArray, index; copyArray = [] index = 0; while (index < strArray.length) { copyArray[index] = parseFloat(strArray[index]); index = index + 1; } return copyArray; } function compGuess () { document.getElementById("compGuessBox").value=compNumber; } function Check() // Assumes: guessBox containes a guess // Results: displays text saying if guess is too high, too low, or correct { var userNumber; userNumber = document.getElementById("guessBox").value; userNumber = parseFloat(userNumber); if (userNumber < randomNumber) { alert("Too Low!"); } if (userNumber > randomNumber) { alert("Too High!"); } if (userNumber == randomNumber) { alert ("Correct!"); } } </script> </head> <body style="background-color:Lavender"> <h1> <div style="text-align:center"> Guess the Number the Computer has Chosen! </h1> <p> <div style="text-align:center"> <input type= "text" id="compGuessBox" size="10" value="" /> <input type="button" value="Click for Guess" onclick="compGuess();" /> </p> <p> <div style="text-align:center"> <input type="button" value="Too Low!" onClick="FUNCTION TO MAKE IT GUESS AGAIN HIGHER" <input type="button" value="Too High!" onClick="FUNCTION TO MAKE IT GUESS AGAIN LOWER" <input type="button" value="Correct!" </p> <p> <div style="text-align:center"> The Computer is Thinking of a Number Between 1-100. Enter your Guess: <input type="text" id="guessBox" size="10" value="" /> </p> <p> <input type="button" value="Check your Answer" onclick="Check();" /> </p> </body> </html> Obviously it doesn't work. My questions a 1.) How can I use an array to display the guesses? 2.) How can I use a while loop to allow the computer and user to take turns guessing each other's numbers? I'm sorry if these are too broad--I genuinely do not know how to proceed from here. I'm going to (hopefully) see the professor to ask these questions as well, but I thought I'd ask here just in case our schedules can't match up. Thank you in advance! I have a checkbox with an id="chk" and a html table (myTable) loaded from a query where one of the columns is the record status (td id="RecStatus"). When I click the checkbox "on", I'm calling a function that I want to go through all records in the table and hide the ones with a RecStatus of "closed". Here's what I have thus far; I know I'm very close but I'm having issues building my array. Code: function killSomeRows(){ var cell=document.getElementById("RecStatus"); var tbl=document.getElementById("myTable"); var numRows=tbl.rows.length; var row=document.getElementById("displayRow"); var i=0 //myArray is set to the # of Rows in my table var myArray = new Array(numRows); //I start my for loop and this is where I am lost for (i=0; i<=numRows; i++){ //In here I want to go through each row in my table and if the "RecStatus" cell = 'Closed' and my checkbox.checked==true, I want to change the style.display = 'none'. //else I want those rows with a RecStatus of 'Closed' to be visible //using style.display = '' if (RecStatus == 'Closed' && chk.checked==true) document.getElementById(row where status is closed).style.display = 'none'; else document.getElementById(row where status is closed).style.display = ''; } } I can get it to hide the 1st record in the table if that record is closed when I click/unclick the checkbox but it appears I do not have the array set up and then the for loop is not going through each record in the array. I'm at a loss....I'm very new to javascript and have been looking at this all day. Any help is appreciated...thanks Cypress my assignment ----------------------------------- write a while loop that prompts user to enter name add their names to an array if they enter "exit" end the prompting sort array and list in sorted order ----------------------------------- this is what i got so far. sooo confused because i cant get the user input into an array. error console says i need ";" before the "var names[loopCounter] = prompt("enter","");" confused about this also var names = new Array(); var loopCounter; loopCounter = 0; while (names != "exit") { var names[loopCounter] = prompt("enter name",""); loopCounter++ } var i; names.sort(); for (i=0;i<names.length;i++) { document.write(names[i] + "<br>"); } |