JavaScript - Multiplying Corresponding Elements In Parallel Arrays
Hi there,
I was hoping for some advice, not really answers as this is part of an assignment. What I have been given is two arrays and I need to multiply the elements in the first with the corresponding value in the second and then save the result into a third array. I am very very new to this and have tried every option i can think of to do this, I entered the result values into the third array just to check the rest of my code is right, this is the only part that has me stumped. Any tips would be hugely appreciated, thank you ) Similar TutorialsWould this code i made <html> <head> <title>Demo</title> </head> <html> <body> <h3>Just a Demo</h3> <script type="text/javascript"> var numbers = new Array ( "1", "1", "1", "1", "1", "1" ); for ( i=1; i < numbers.length; i++ ) { alert ( numbers[i] ); } </script> </body> </html> Would that be an exmaple of arrays with elements intilized to 1(true) Hello, I would like to create a form that calculates the area of a floor or wall. The user will input the length/height and width dimensions into two input fields and then click calculate. I simply need a script that multiplies the two fields together and puts the answer in a third read-only field. Any help much appriciated Kind regards, Mike I am working on a job calculator. I have 2 txt input boxes titled "project_rate_field" and "project_time_field" as well as a third box .. "project_pay_total_field" for output.. I need to multiply the rate field and the time field and output the total into the third box. I've never really used javascript before so I dont know much about it or how to write it but im trying to learn. Here is my .js file ... Code: function project_pay_details() { var rate = document.getElementById("project_rate_field").value; var time = document.getElementById("project_time_field").value; var total = (rate * time); project_pay_total_field.value = "$" + total; } And here is my .html file 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> <script language="javascript" type="text/javascript" href="functions.js" /> <style> .wrap { float: right; } #project_pay { float: left; margin-right: 15px; line-height: 38px; font: 10px Arial, Helvetica, sans-serif; color: #bbb; } #project_pay_details { border-top: 1px dotted #ddd; padding-bottom: 10px; margin-top: 10px; float: right; width: 100%; } .field { border: none; line-height: 38px; font: 20px Arial, Helvetica, sans-serif; color: #666; width: 100px; font-weight: bold; margin-top: 6px; } </style> </head> <body> <form id="project_pay_details" name="form1" method="post" action="" class="editable"> <div class="wrap"> <div id="project_pay">Pay Rate<input type="text" name="project_rate_field" id="project_rate_field" class="field" value="10" />/ hr</div> <div id="project_pay">Total Hours<input type="text" name="project_time_field" id="project_time_field" class="field" value="0" /></div> <div id="project_pay">Project Total<input type="text" name="project_pay_total_field" id="project_pay_total_field" class="field" readonly="readonly" value="0" /></div> <input name="project_pay_details_refresh" type="button" value="Refresh" onClick="project_pay_details()" /></input> </div> </form> </body> </html> I need to know what im doing wrong because this obviously doesnt work. Hello everyone I have just found this wonderful forum through Dr Google whilst looking for an answer to my incredibly frustrating question! I am an OU student it is for an assignment I just cannot find the answer in any of the books and searching the net has got me nothing but so far wasted 3 hours Here is the code snippet: Code: // candidates var candidateArray = ['Mr R Green...', 'Ms O Brown...', 'Ms Y Black...', 'Mr G White...', 'Ms B Grey....','Ms I Blue....', 'Mr V Pink....']; // online votes var onlineVotesArray = [21,47,23,11,56,47,30]; // paper votes var paperVotesArray = [12,4,20,11,5,4,17]; //total votes var totalVotesArray = (candidateArray.length); First I had to add a new array called totalVotes and assign a length to it the same as candidateArray, I have done this in the last 2 lines I think this is correct, the question did stipulate that if the candidate array was changed then so would the total votes array hence linking it via length. Now here is where I am at a complete loss The exact wording is as follows: Use a for loop to calculate the total votes for each candidate according to the following structured english: for each array position add the element at that position in the online vote array to the element at the position in the paper vote array. store the result at the corresponding position in the total votes array end for I have been scratching my head for 3 hours now, I have to have this assignment uploaded before midnight to my tutor or I am in the poo Any help really really appreciated. Thanks in advance 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. /* First of all thank you for reading my thread and giving time to help me. Here goes my question: How to sort this array? MY PRIORITY COLORS array: ------------ green , yellow ALL COLORS array : <---- this will be your main array. ----------------------- pink , green , orange THE RESULTS: ( the results after you sort) (Not sorted by alphabetically, but sorted by the priority colors) ---------------- green , pink , orange I hope you could help me solve this javascript sorting problem. Thank you! Code: <HTML> <HEAD> <TITLE>Listing 4.4</TITLE> <SCRIPT TYPE="text/javascript"> //DEFINE METHOD function displayInfo() { document.write("<H1>Employee Profile: " + this.data[0] + "</H1><HR /><PRE>"); document.writeln("Employee Number: " + this.data[1]); document.writeln("Social Security Number: " + this.data[2]); document.writeln("Annual Salary: " + this.data[3]); document.write("</PRE>"); } //DEFINE METHOD TO GET EMPLOYEE INFORMATION function getInfo() { var menu="0-Exit/1-Name/2-Emp. #/3-Soc. Sec. #/4-Salary"; var choice=prompt(menu,"0"); if (choice != null) { if ((choice < 0) || (choice > 4)) { alert ("Invalid choice"); this.getInfo(); } else { if (choice != "0") { this.data[choice-1]=prompt("Enter information",""); this.getInfo(); } } } } //DEFINE OBJECT function employee() { this.data = new Array(4); this.displayInfo=displayInfo; this.getInfo=getInfo; } newEmployee=new employee(); </SCRIPT> </HEAD> <BODY> <SCRIPT TYPE="text/javascript"> newEmployee.getInfo(); newEmployee.displayInfo(); </SCRIPT> </BODY> </HTML> I am currently taking a Javascript certification course, this is a exercise given (final code) I don't completely understand what is going on though, could someone explain to me Code: this.data[choice-1]=prompt("Enter information",""); that part? I don't understand why, [choice-1] I don't fully understand why an array is even needed here? Hi. I am fairly new to JavaScript. I am having some troubles with arrays. I am using Chrome 12 beta. Here is a brief version of the code I am having trouble with Code: var array=new Array() array[0]=new Array() array[0][1]=new Array() var array[0][1]=[ 3, 1, 4, 1, 5, 9, 2, 6, 5, ... ]; I do not want to use "array[0][1][n]" because my array has too many items to do that and it is just plain annoying to change the numbers that way. I get an error on the "var buffers[0][1]=[" line saying: "Uncaught SyntaxError: Unexpected token [" What is the problem in my code? Thank you ahead of time. ---mint Hi could someone help with this javascript. i dont know where to start with the script which is in bold. Program to report the results of an election. // candidates var candidateArray = ['Mr R Green...', 'Ms O Brown...', 'Ms Y Black...', 'Mr G White...', 'Ms B Grey....','Ms I Blue....', 'Mr V Pink....']; // online votes var onlineVotesArray = [21,47,23,11,56,47,30]; // paper votes var paperVotesArray = [12,4,20,11,5,4,17]; // total votes -- to be initialised below var totalVotesArray; // Add code to // -- initialise totalVotesArray with a new empty array of the same size as candidateArray // -- use a for loop to add the online and paper votes for each candidate and store the result at the corresponding position in the total votes array. I have a choice when creating a new API that I would like other peoples opinions on. Do I use a single Array or Multiple arrays such as: Code: array[1][1] = "ID[56]NAME[Hello World]START[10]"; OR Code: ID[1][1] = 56; Name[1][1] = "Hello World"; Start[1][1] = 20; The API is used for animations so is very heavy work, but would using around 15 multidimensional arrays be too much and a single one be preferable??? Thanks 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> I have a quick question with multiple array and random numbers. If i generate my random numbers in one array, how would i take a selection of those numbers and put them in another array? Ex: array 1: 25, 34, 38, 40, 22, 49 want to move numbers between 30 and 50 to another array. array 2: 34, 38, 40, 49 is it as simple as for loops and if statements setting the conditions? do i use a sorting method? (selection? bubble?) any help would be appreciated. hi i have two arrays and i need to know which strings are in both arrays. i know how to do the bit if the string is in both but i don't know how to compare them as such. thanks If anyone is planning on buying "ICAB4225B Automate Processes" in relation to a TAFE/College/School course, I suggest getting the teacher to actually READ the book before they use it. Tonight has been a HE-Double Hockeysticks (Not sure on language in this forum) of fixing mistakes the book has made. Double commars inplace of singles, singles inplace of doubles, single brackets, whole chunks of text that are wrong. In one place in the book it tells me to copy the text in blod and there is none. Anyway.... The code that the book has made me piece together over the last few questions has left me with: Code: <script type = "text/javascript"> { var counter = 0 var NoOfItems var ItemsNames = new Array() NoOfItems = prompt ("How many items do you want to hock?",""); for (NameCount=0; NameCount<NoOfItems; NameCount++) { ItemNames [NameCount] = prompt ("What are the names of your items?",""); } document.write ("<form name='myform'><br><table>"); while ( counter < NoOfItems) { document.write ("<tr><td><value>Enter the price of the " + ItemNames [count] + "</td><td><input type='text' name='" + ItemNames [count] + "'></td></tr>"); counter++ } document.write ("<tr><td><input type='submit' value='Submit Details' onClick='validateform'</td></tr></table></form>"); } </SCRIPT> The problem I am having it with the Array. I dont think that var = new Array is correct but thats what my text book is telling me. Any help? Hi, I am trying to merge the values of 2 arrays. array 1 = 1, 2, 3, 4, 5 array 2 = a, b, c, d, e Resulting in: array 3 = 1-a, 2-b, 3-c, 4-d, 5-e etc both arrays that will be used originally will always of the same length. Both arrays will contain numbers Can you please help? Thanks Im working on a program where the user enters a line of numbers and then can either sort them in order or can display the minimum number. Both those seem to work, but for some reason I keep getting three -1 values in my array. So the minimum value is always -1 and when I sort it comes back -1-1-1[numbers i enter]. I cant seem to figure out why my code is doing that. Code: private int[] buildArray(String line) { int[]arr = new int[line.length()]; arr[0] = 0; for (int i = 1; i < line.length(); i++){ arr[i] = Character.digit(line.charAt(i),10); } return arr; } private int findMin(int numbers[]) { //PRE numbers.length >= 1 int min = numbers [0]; for (int i = 1; i < numbers.length; i++){ if (numbers [i] < min) { min = numbers [i]; } } return min; } private String makeString(int numbers[]) { //PRE numbers.length >= 1 int i = 0; String s1 = new String (""); while (i < numbers.length){ s1 = numbers[i] + s1; i++; } return s1; } private void sort(int numbers[]) { for (int i = 1; i< numbers.length; i++){ int j = i-1; int temp = numbers[i]; while (j >= 0 && temp > (numbers[j])){ numbers[j+1] = numbers[j]; j--; } numbers[j+1] = temp; } } Input: 3,1,2,88 output: Min Value = -1 Line 1 Sorted = -1-1-101288 Any type of help would be very appreciated, Im very new to this still. Do arrays retain its data outside of a function. The reason why i asked this is because i created a global array and then a function. In the function i assaigned values to the global array but when i try to access the global array it gives me a "undefined" or "null" error. Code: var myArray = new Array(); var count = 0; function populate(){ for(i=0; i < 5; i++){ myArray[i] = count++; } } |