JavaScript - Average From Loops Without Arrays Nor Functions?
I've now got to form an average of snowfall inputs, taken from looped prompts, however I'm not allowed to use arrays or functions...
Almost every example I see uses arrays, such as this one he http://www.codingforums.com/showthread.php?t=4313 Is it possible to not use arrays to form the average? Please describe how to do this in general terms, as was highlighted in that link ^^^ I want to learn, not copy, although one can be derived from the other... What I haveso far, assume all vars have been announced. Code: for (var d=1; d<=numofinputs; d=d+1) { input = prompt("Enter a data input" + d) } Is it possible I'm attempting this in too general a manner? ie, running before I can walk. Similar TutorialsI 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. 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 am looking to get a loop which runs through a series of divs (each with an attribute called "position" followed by 5 comma separated values). for each of these divs i need the 5 comma separated values (from position) to be assigned to variables. I have the rest of the code sorted out i just cannot get the original variables. Examples: divs look like this... Code: <div position="100,100,50,50,1"></div> There are no limits on the number of these divs but there will never be 0. What i want is something to look like this. For each div, var s = string of attribute (position) values (output:a,b,c,d,e) split string to create var a = a var b = b var c = c var d = d var e = e I from those 5 vars can do what i need. and i know that vars a,b,c,d,e,s will all be overwritten in when it comes to the next div... that is planned. How does my array look so far? thanks I think so what i was supposed to do was insert a script element that contains the function amountTotal() then add commands to the function such as 1 declare variable named total, set intial value to 0 2 create a FOR LOOP that loops all values in amount array. add current value of array item to value of total variable 3 when completed return value of total variable This is what I came up with tell me if this makes sense Thanks Quote: title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="list.js"></script> <script type="text/javascript"> function amountTotal() { totalAmount=0; for(var i=0; i<amountTotal.length; i++){ total+=amount(i); { return total; } </script> </head> Does this seem right or is my format all wrong? if so what should i have instead? thanks Hello, Problem 1: I have a function and it sets a value to a certain number according to the input. However, I don't want the function to print out the value to the screen, but instead temporarily save it for me to use throughout the whole script. I am a newbie and please help me. For example, I make this code: function add1(x) { var x = x + 1 return x; } and I call the function: add1(0); document.write("value = " + x + "<BR>"); Whenever I do this, document.write doesn't print out value = 1, it doesn't even print anything except for the headers, etc. Is there anyway to set the var x to be a value valid throughout the whole script instead of just the function itself? I really need help on this, thanks. Problem 2: I want to get a code working. Basically, I use a ram to "ram the gate". I set the damage done each turn, and the Gate's Health too. So for example, my ram's damage is 10 and the gate's health is 200. It would take 20 times to totally breach the gates(i.e., for gate health to become 0). When I use the following code, the total damage is the same throughout the whole looping until the gatehealth reaches 0 which makes it boring, is there anyway to modify or improve the script such that when I loop, the MiscDamage would be different for all the turns? thanks! Once again I apologize for asking such a noob-ish and very strange.... question. Quote: <script language="JavaScript" type="text/javascript"> <!-- // Begin function RamGates(Ram, Attack, Gate) { //introducing variables to be used var BaseDamage = 0; var FullDamage = 0; var MiscDamage = 0; var TotalDamage = 0; var GateHealth = 0; switch (Ram) { //ignore this part just comparing ram types case "Explosive": BaseDamage="10"; break; case "Wooden": BaseDamage="20"; break; case "Steel": BaseDamage="30"; break; case "", "?": default: BaseDamage="Failed to recognize Ram"; } switch (Attack) { //ignore this just comparing attack values case 0: FullDamage = BaseDamage; break; case 1: FullDamage = (BaseDamage*2)-8; break; case 2: FullDamage = (BaseDamage*2)-6; break; case 3: FullDamage = (BaseDamage*2)-4; break; case 4: FullDamage = (BaseDamage*2)-2; break; case 5: FullDamage = BaseDamage*2; break; case "", "?": default: FullDamage="Failed to recognize Attack"; } switch (Ram) { //this part is what i need help on, i need the loop function to keep using this to generate different "lucky damages" each time to make it interesting, i.e., first ram = 11 second ram = 16 third ram = 14 and so on..... case "Explosive": MiscDamage = Math.floor(Math.random()*21+10); break; case "Wooden": MiscDamage = Math.floor(Math.random()*6+0); break; case "Steel": MiscDamage = Math.floor(Math.random()*11+5); break; case "", "?": default: MiscDamage="Failed to recognize Ram"; } switch (Gate) { //ignore this part just comparing gate types to generate gate health case "Wooden": GateHealth = 50; break; case "Brick": GateHealth = 75; break; case "Small Stone": GateHealth = 90; break; case "Large Stone": GateHealth = 120; break; case "Granite": GateHealth = 140; break; case "Iron": GateHealth = 175; break; case "R Iron": GateHealth = 190; break; case "Thick Iron": GateHealth = 210; break; case "Steel": GateHealth = 230; break; case "R Steel": GateHealth = 250; break; case "Thick Steel": GateHealth = 275; break; case "Steel Iron Mix": GateHealth = 280; break; case "Thick Steel Iron Mix": GateHealth = 300; break; case "Strong Ruby Steel Mix": GateHealth = 400; break; case "Strong Sapphire Steel Mix": GateHealth = 450; break; case "R Thick Large Diamond Steel Mix": GateHealth = 500; break; case "", "?": default: GateHealth = "Failed to recognize Gate"; } TotalDamage = FullDamage + MiscDamage; with (document) { write ("Soldiers, " + "RAM THE GATES!" + "<BR>"); } while (GateHealth >= 0) //loops until gate health is lower than 0 { //need help! how to make it such that the loop will rerun the switching of ram for generating random misc(lucky) damages document.write ("Lucky Damage done = " + MiscDamage + "<BR>"); document.write ("Total Damage done = " + TotalDamage + "<BR>"); var GateHealth = GateHealth - TotalDamage document.write("Current GateHealth = " + GateHealth + "<BR>"); } } RamGates("Explosive", 5, "R Thick Large Diamond Steel Mix"); //function calling // End --> </script> Hello everyone I am having trouble with a project i am supposed to be doing which is to turn structured English into coding joined with the code i am about to post !! This is the code i have written so far that works: var contestantNamesArray = ['Tom and Nazia', 'Pat and Dan', 'Sandra and Kofi', 'Ian and Adele', 'Paul and Costas']; var judgesPointsArray = [2,1,5,4,3]; var audiencePointsArray = [4,5,2,3,1]; var combinedPointsArray = new Array (5) for (var couple = 0; couple < combinedPointsArray.length; couple = couple + 1) { combinedPointsArray[couple] = judgesPointsArray[couple] + audiencePointsArray[couple]; } var maxCombinedPoints = 0; for (var couple = 0; couple < combinedPointsArray.length; couple = couple + 1) { if (combinedPointsArray[couple] > combinedPointsArray[maxCombinedPoints]) { maxCombinedPoints = couple; } } document.write('The maximum number of points was ' + combinedPointsArray[maxCombinedPoints] + '<BR>'); document.write('The couple(s) scoring the maximum were' + ':' + '<BR>'); Now with that code there i have just posted, I am supposed to take this structured English below and combine them together but cannot work out how to link or code it to get it to work. write out a heading for the list of couples scoring the maximum declare a variable to keep count of how many couples scored the maximum value and initialise it to zero for each couple if this couple scored the maximum write out the couple's names increase the count of couples who scored the maximum value end if if a dance-off is required write out that a dance-off is required else write out that a dance-off is not required end if end for I have tried myself but i am stuck at how to link the contestantNamesArray with the rest of the code in order to be able to display the couples who scored the maximum points and store it in a new variable and then write out the names. Sorry if i have posted wrongly this is my first time and i am a new learner to JavaScript trying to learn basics. Thank you anyone in advance and if you need any further information i will provide anything you need. Gary I am having an issue with this script I wrote. Actually it works the way it is now, but not the way I want it too. This is a random raffle ticket number generater. The guys at the fire department where talking about selling 300 tickets and discussing how they were going to select and call the numbers. It got me thinking and inspired to start messing around with javascript again. It all starts with index.html and a form w/ a button and textarea. When a user clicks the button it will generate a random number and insert it into the textarea. This is accomplished by the Generate(); function that is in Genny.js an external js file. Code: <h2>Raffle Ticket Number Generator</h2> <form name="theform"> <input type="button" name="pickNumber" value="Pick a Winner" onclick="Generate();" /> <br /><br /> <textarea cols="40" rows="25" name="winnersCircle">Winning Numbers Will Display Here! </textarea> </form> This much works just fine. Now onto Genny.js Code: //initialize counter and array count = 1; winners = new Array(); function Generate(){ //generate a random number from 0-300 var random_number = Math.floor(Math.random()*301); //checks output of Math.random() against winners array to see if number has been used already for (i = 0; i < winners.length; i++ ) { if ( winners[i] == random_number ) alert("I am so sorry... we have accidently drawn a duplicate number! Please pick again."); } //add the number to the array winners[count] = random_number; //increment the counter count++; //display the stored random number document.theform.winnersCircle.value = winners.join("\n"); } This much works...somewhat! It generates the random number and checks the winners array to see if it is already used. If it wasn't used it adds the number to the array, increments the counter, and then displays the number in the textarea of the form, as it should. If the number was used it alerts the user, once the user clicks the button to accept the alert it carries on with the script and adds it to the array again and also displays it. This is not what I want it to do. If the number was used I do not want it added to the array or displayed. I would also like it to regenerate another number without the alert. The alert was wrote in to assist me in checking to see if it was finding a duplicate number, thats all. As an extra, is there a way to also add a numbered list to the results. To show the sequence of the ticket draw. I have messed with this for days and rewrote it over and over. I have used different loops and conditional operators to try and solve this problem. But to no avail. Here I am, asking not for the answer but a push in the right direction. Any help would be great, this is becoming an obsession trying to make it work. The code above is the last attempt at this point. Everything else has returned no values or just errors. Thanks in advance! 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. Hey all, I am confused about the true difference between the two below examples. Code: first example: // Demonstrating a problem with closures and loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = function() { document.write(theItem + “ < br / > ”); } } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate through the length of myArray, assigning the current index of myArray to theItem variable. We declare closureArray 4 times as an anonymous function. The anonymous function in turn declares the predefined write() function, which is passed parameters. Since write() is in closureArray() a closure is created??? During each iteration, theItem is reassigned its value. The four closures reference this value. Since they reference this same value and since this value is reassigned ultimately to the value of the fourth index position, tHe time we execute closureArray later on, all four closures output the same string. This is because all four closures are within the same scope "the same environment" and therefore are referencing the same local variable, which has changed. I have a couple of problems with this example: 1) I thought a closure is a function that is returned - the inner function is not returned above. 2) theItem is not even a local variable of the parent function (closureArray) - I thought in order for a closure to work, the inner function only accesses the local variables of the outer function, but in this case the local variable is defined OUTSIDE of the parent function. 3) The guy says the "the four closures are sharing the same environment." The thing is even in the second example, they are sharing the same environment. Second example: Code: // A correct use of closures within loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); function writeItem(word) { return function() { document.write(word + “ < br / > ”); } } // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = writeItem(theItem); } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate over the length of myArray (4 times), assigning the index of myArray to theItem variable. We also return a function reference to the closureArray during each iteration (closureArray[i]), where i is index number so we assign 4 functon references. So when we iterate through myArray, we immediatelly call the writeItem() fucntion passing an argument of theItem at its current value. This returns a child anonymous function and when that child function is called, it will execute a block that calls the predefined write() method. We assign that returned anonymous function to the variable closureArray. Hence, closureArray holds a reference to that anonymous function. So closureArray during each iteration holds a reference to the anonymous function and we later call closureArray, which in turn calls the anonymous function, therefore calling the predefined write() function to output the local variable of the parent function. This outputs each distinct index of myArray. QUESTION: This is because since we created the closure, when we call writeItem, passing theItem argument, since theItem is a local variable of the parent function of the closure, it is never destroyed when we later call closureArray (the reference to the child anonymous function)? Yet weren't we using a closure in the first example as well? So whey wasn't those variables preserved? I don't think it has anything to do with assigning a returned anonymous function to closureArray. Even though an anonymous function creates a new memory position in the javascript engine, therefore not overwriting the other function references we create during the iteration, it's still referring to a local variable declared outside the reference. So if it's about the closure retaining value of parent's local variable even after exiting the parent function allowing for the current indexes to be preserved, then why did the closure in the first example fail to retain each index? Thanks for response Hi, new to this forum but have a quick question about arrays, I've been working on this all night, and I'm at a loss. I'm trying to calculate the gpa of a user by using arrays and functions. Everything seems to be working besides two things.
The array that contains the class names (className[]) always includes an extra two variables: my sentinel value which is finish, and "undefined"
The arrays at the end won't produce a number when multiplied together. creditData[] and qualityPoints[].
Also, if you have any suggestions on my code, I'd appreciate it. <script type="text/javascript"> <!-- /**************************************************************** ** PrintExplanation - prints a message containing instructions to the user without ** any variable needed. ** Inputs:None ** Outputs:None ****************************************************************/ function PrintExplanation() { alert("This program will calculate your Grade Point Average for any given semester. Please enter only graded classes, no Pass/Fail Classes."); } /**************************************************************** ** GetValidNumberInput - Error checks a number between two constraints. ** Inputs: promptString - allows the user to insert a string in order to be asked. ** lowerNum - the lower constraint you want to be compared. ** upperNum - the higher constraint you want to be compared. ** Outputs: numCredits ****************************************************************/ function GetValidNumberInput(promptString, lowerNum, upperNum) { var promptString; var lowerNum; var upperNum; var numCredits; numCredits=prompt(promptString); while(numCredits<lowerNum || numCredits>upperNum) { numCredits=prompt(promptString); } numCredits=parseFloat(numCredits) return numCredits } /**************************************************************** ** CalculateGPA - Calculates the users GPA ** Inputs: totalCredits: The total amount of credits determined by the user. ** totalQualityPoints: The total amount of quality points determined by the user. ** Outputs: gpa - the users final grade point average. ****************************************************************/ function CalculateGPA(totalCredits, totalQualityPoints) { var totalCredits; var totalQualityPoints; var gpa; gpa=totalQualityPoints/totalCredits return gpa; } function GenerateGPAReport(totalCredits, totalQualityPoints) { } /**************************************************************** ** ConvertGradeToPoints - Converts a letter given by the user into a number corresponding to grade points. ** Inputs: grade - the letter of the grade the student recieved in the course. ** Outputs: points - the number value of the grade that was input by the user. ****************************************************************/ function ConvertGradeToPoints(grade) { var grade; var points; if(grade == "A" || grade== "a") { points=4 } else if(grade == "B" || grade == "b") { points=3 } else if(grade == "C" || grade == "c") { points=2 } else if(grade == "D" || grade == "d") { points=1 } else if(grade == "F" || grade == "f") { points=0 } points=parseFloat(points); return points; } //--> </script> </head> <body> <script type="text/javascript"> var promptString; /*Declares Variables*/ var className; var numOfClasses; var grade; var semester; var numCredits; var lowerNum=1; var upperNum=4; var class1; var i=0; var counter=0; var totalCredits=0; var totalPoints=0; var grade; var counterCredits=0; var counterGrade=0; var points; var gpa; var qualityPoints; var creditData; var gradeData; var x=0; var totalQualityPoints=0; PrintExplanation(); var className = new Array(i); semester=prompt("Please enter the semester you would like to calculate your GPA for."); document.write("Grade report for " + semester + "<br />"); while(class1!="finish") /*Stores the names of the classes taken into an array*/ { class1=prompt("Enter the Class name, or finish to end"); className[i]=class1 i++ } while(counter<=i) /*writes the classes in the array from top to bottom*/ { document.write(className[counter] + "<br />"); counter++ } var creditData = new Array(i) while(counterCredits<=i) /*counts the total number of credits for all the classes*/ { numCredits=GetValidNumberInput("How many credits is " + className[counterCredits] + " class worth?",1,4) creditData[counterCredits]=numCredits totalCredits=totalCredits + numCredits counterCredits++ totalCredits=parseFloat(totalCredits); } var gradeData = new Array(i) /*collects information about grades in an array*/ while(counterGrade<i=) { points=prompt("What grade did you recieve in " + className[counterGrade] + "?"); points=ConvertGradeToPoints(points) gradeData[counterCredits]=points totalPoints=totalPoints+points counterGrade++ } while(x<=i) { qualityPoints=creditData[x]*gradeData[x] totalQualityPoints=totalQualityPoints + qualityPoints x++ } gpa=CalculateGPA(totalCredits, qualityPoints) document.write(gpa); </script> </body> Ok so im stuck (again) and going to try another late night getting this program to do what I want. I assume many of you have heard of ducci's game, then here is a link which will probably make it a bit more obvious http://demonstrations.wolfram.com/TheFourNumberGame/ so basically making a program that can do that, there is obviously many easy-er ways to go about doing this including... Code: function difference(numberArray) { var numLen=numberArray.length var iteration=0 var diffArray var zero document.writeln(numberArray+'<br>') do { diffArray=[] for (var i=0;i<numLen;i++) diffArray.push(Math.abs(numberArray[i]-numberArray[(i+1)%numLen])) numberArray=diffArray zero=true for (var i=0;i<numLen;i++) if (numberArray[i]) zero=false document.writeln(numberArray+'<br>') iteration++ } while (!zero) document.writeln('Iterations taken : '+iteration+'<br>') } difference([24,44,81,149]) so that codedoes everything CORRECTLY and displays it all properly... but not how I'm allowed to do it according to the question as that just has everything done under one function in one easy go ... the way I have been told to do it is by utilising 3 functions In the code below you can see how it is meant to be set out, with the comment explaining/saying what each function should do. Code: <script type="text/javascript"> //will tell you the difference between firstNumber and SecondNumber. // Number returned will always be ABOVE or Equal to 0 so will need to subtract from the higher number. function difference () var firstNumber; secondNumber; document.writeln(numberArray+'<br>') { } //will calculate the total of numbers in the array to see if they equal 0 and display total //The iteration from each square to the next square must continue until all the numbers are zero. //use function sum() that calculate the total of the numbers //If the value returned by this function is 0 then all the individual values must be zero because none of them is negative. // Write the function sum(), which should accept an array numberArray and return the sum of the numbers. function sum(numberArray) {} //makes a new array containing the differences between the pairs of numbers and then display it. //code the process that calculates a new array containing //the differences between all the pairs of adjacent numbers, using the difference() function you have already written. function calculateDifferences(numberArray) var difference; {} //Array which holds the numbers at the four corners of the square. var numberArray = [24,44,81,149];//Edit this line to change the starting numbers document.write(numberArray +'<BR>'); </SCRIPT> as im not allowed to use the first code and have to have it this long way I cant really work out how to do it :/ (im being stupid) like always i'd like to say I do want to learn so push me in the right direction and hint rather then tell me the answer as i'd prefer to make mistakes and learn to get around them etc (im currently NOT at home aswell so dont have any of my textbooks due to family issues arising and I do need to get this done so everything will be done online including research etc.) so where should I start as tbh the way it's done in the first example is well.. correct :/ and im not sure how to get it to use the 2 arguements to calculate each and every difference from in the array (and then looping around again from the last number onwards.. So I am making a function that takes numbers and when you enter a letter than it's supposed to skip to the if statement and give the average. The problem is that it doesn't seem to add the number to total on each loop. the first code is what I am working with. I was supposed to take a While loop and turn it into a do-while loop. The second peice of code is the original while loop. } Code: var finding_average = function() { var total = 0, count = 0, number; alert("Enter the numbers to average. Enter any non-number to stop."); do { number = parseInt( prompt("Enter a number") ); total = total + number; count++; } while ( !isNaN(number) ); var average = total / count; if ( isNaN(average) ) { alert("You didn't enter any numbers."); } else { alert("The average is: " + average); } Code: var finding_average = function() { var total = 0, count = 0, number; alert("Enter the numbers to average. Enter any non-number to stop."); number = parseFloat( prompt("Enter a number") ); while ( !isNaN(number) ) { total += number; count++; number = parseFloat( prompt("Enter another number") ); } var average = total / count; if ( isNaN(average) ) { alert("You didn't enter any numbers."); } else { alert("The average is: " + average); } } hi I need to find the average number in javascript. I have been working on it for a while but i am getting no where yes i am new to javascript and to be honest it is doing my blonde headed brain in. can someone please take a look at it and advise me on what i am doing wrong. it is the only bit of javascript that i have to do in the course but it carries a high mark of which i can not afford to lose Any way the question is : "Write code to calculate the average height and write it out in the browser window" Code: <HEAD> <TITLE> average </TITLE> <SCRIPT LANGUAGE = "JavaScript"> //Experimental results of Table 1 stored in arrays. var Height = [15,16,17,18,19]; var Number = [2,1,6,4,2]; //Part (ii). //Write code to declare and initialise new array to represent the third row of the table. var avg = new Array(5) var avg = ["60","80","187","180","114"] ; avg[0] = "60"; avg[1] = "80"; avg[2] = "187"; avg[3] = "180"; avg[4] = "114"; //Part (iv). //Write code to calculate the average height and write it out in the browser window. avg = 0; for (var count = 1; count <= 5; count = count + 1) Array.average = function(){ var avg = 0; for(var a = 0; a < this.length; a++){ avg += this[a]; } return avg / this.length; }; document.write('average height is ' +avg + '<br>'); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> sorry for my ignorance thanks in advance kelly XXXXX I need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* Hi i need to find the highest average from all of the averages entered in this code, but i have to use an if statement only, no arrays. Could some one help please? Code: // ** Work out average ** // average= readingSum/totalReadings // ** Put average into a category and display everything ** // if(average<5) { catergory1=alert("Location is " + region + "\nNumber of weekly readings taken is " + totalReadings + "\nTotal of readings is" + readingSum + "\nAverage is" + average + "\nLocation is Dry"); } else if(average>=5 && average<20) { catergory2=alert("Location is " + region + "\nNumber of weekly readings taken is " + totalReadings + "\nTotal of readings is" + readingSum + "\nAverage is" + average + "\nLocation is Normal"); } else if(average>20) { catergory3=alert("Location is " + region + "\nNumber of weekly readings taken is " + totalReadings + "\nTotal of readings is" + readingSum + "\nAverage is" + average + "\nLocation is Wet"); } // ** Find Highest average ** // Thanks. I need to allow a user to enter 3 values, then display the average between them... I am having some real issues with the average, Thanks! var quiz1 = prompt("What is the score of your first quiz?", "") document.write("Return Value: "+quiz1, '%',("<br />")); var quiz2 = prompt("What is the score of your second quiz?", "") document.write("Return Value: "+quiz2, '%',("<br />")); var quiz3 = prompt("What is the score of your third quiz?", "") document.write("Return Value: "+quiz3,'%',("<br />")); average= ("quiz1"+"quiz2"+"quiz3") /3 document.write(average,("<br />")); helow to every one im new here....i hope im welcome here can i ask how to make this problem? input 20 number and print the average of the numbers....any one can help me please... Hello, I'm new here and a newbie to the world of java script. I am taking a CIT class and we just moved on to java script which i am having trouble with. My assignment is to calculate the average, number of passed, and number of failed grades according to this list (65, 80, 85, 55, 90, 70, 62, -1) where it terminates at -1 and the passing grade is >=70. Any help is appreciated! Hi all, I am in a non-major class called webprogramming working with javascript and I'm having an issue with a specific code wondering if someone could tell me what's wrong! So I am suppose to compute and return the average of all values in a given array named customerBalance, the array holds the amount of "what customers owe my business" (I dont own a business) and each item in the array holds the "customers balance", i also have to use a for() to process the array and calculate the average and divide by customerBalance length, and finally return the average. Here is my code so far <script> function average() { customerBalance for(i=0,i++) sum(customerBalance) total=sum/5 return average; }; </script> I know that this is COMPLETELY wrong, I am not sure on how i start typing the array, please don't be harsh I would really like to know how to do this. Thank you and have a great day Hi, First i don know if im posting at the right place or if you even take request here, feel free to direct me to the right place. What i am looking for is someone to make a simple counter for me. Basically i want that every time i press a certain key on my keyboard it will increase the counter amount and would then divide it by 60 every hour. Actually im looking for it to only show that average and refresh every hour. So it would start at 0 then update after the first hour and so on. (I also need a graphical interface) I have very few knowledge in coding and would very appreciate if someone could do that for me. Thank you ! Reply With Quote 01-10-2015, 11:39 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts I don't think this is something you would do with JavaScript. I think you need a ".exe" (on Windows) program. And that's a lot more complex. The problem is your request to capture a certain key, presumably no matter what window is at the front. Normally, within a given window, you can only capture a key that is intended for that window. I don't think this is a very easy thing to do. |