JavaScript - Multiple Arrays
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. Similar TutorialsYou've probably seen this many times with two dynamic linking select boxes that deals in form or another deal with countries and then cities for the second one or something similar well I have another question about that. I've looked at a few others and well their coding is so different then mine that I don't want to use code for my own project that I don't understand in case I need to reuse it for some other reason down the road. The user selects a country and with the users selection it passes the countryid as a variable through jquery's ajax fuction as a post parameter to a php process page in which it goes to a table and matches the country id with the db field called country_id in the arenas table. With all the records that matches that countryid it selects the arena name and city that the arena is in and displays it as an option tag now I'm trying to figure out with muliple entries how can I pass the results back to the form page and insert it into the arenas dropdown box. Following is my coding separated out for you. I only included the necessary parts. All help would be greatly appreciated. form page Code: $('#countryid').change(function() { var countryid = $("select#countryid").val(); var dataString = 'countryid='+ countryid; $.ajax({ type: "POST", url: "processes/booking.php", data: dataString, success: function() { } }); }); <div class="field required"> <label for="countryid">Country</label> <select class="dropdown" name="countryid" id="countryid" title="Country"> <option value="0">- Select -</option> <?php $query = 'SELECT id, countryname FROM countries'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['countryname']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="arena">Arenas</label> <select class="dropdown" name="arenas" id="arenas" title="Arenas"> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> php process page PHP Code: $countryid = (int)$_GET['countryid']; $query = "SELECT * FROM `arenas` WHERE `country_id` = '$countryid'"; $result = mysqli_query ($dbc, $query); while ($row = mysqli_fetch_array($dbc, $result)) { echo '<option value="'.$row['arena'].'">'.$row['arena'].' - '.$row['city'].'</option>\n'; } 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 hope someone can help me. I'll be honest and say I don't know much about javascript, but am fairly comfortable in html. I am building a website that will have multiple image swaps on multiple pages. I am building this in wordpress, and I'm guessing that means my approach will be different than if I wasn't using wordpress. Here's how one page would work: There are 10 images shown. 1,2,3,4,5,6,7,8,9,10. When number 1 is clicked on, I want a new image - 1a. When 2 is clicked on, 2a. So there are 20 different images in all on a given page. Also, I want the user to be able to click on the image again to restore the original image. I would prefer onclick to onmouseover. There will be literally dozens of pages like this on the site, managed by wordpress, so hundreds of images to swap. Basically the first image is a question - the second image is the answer. Is this possible? 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. 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? 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! 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> Got this script from the Sam's Teach Yourself Javascript In 24 Hours book, and I'm a little confused with regards to this script I came across, or more specifically, the part of the script I've outlined in red. Code: <script language="javascript" type="text/javascript"> function numcompare(a,b) { return a-b; } nums = new Array (17, 902, 30, 10, 200, 4, 506); sortednums = nums.sort(numcompare); output = sortednums.join(", "); document.write(output); </script> I really don't understand how the numcompare() function works, and the book doesn't explain it very well. Any help with deciphering this piece of code? Thanks in advance. Hashim. Code: <script type="text/javascript"> var authors = ['Ernst Hemingway','Charlotte Bronte','Dante Alighieri','Emily Dickinson']; </script> <script type="text/javascript"> document.write('<p>The first author is <strong>'); document.write('authors[0] + '</strong> </p>'); </script> I'm getting a syntax error on the last line ? I can't see the error, I closed the strong tag, closed the p tag. Put the line in a string, why won't it write the string ? I'm a newbie of JS and don't know if I have got the right terms in my question. I want to lowercase all the arrays: Code: <script> var txt = [ ["Cats","Dogs","Rabbits"], ["Fish","Bones","Carrots"] ] document.write(txt[0][1] + " love eating " + txt[1][1]); </script> I know I can do something like this: Code: document.write(txt[0][1].toLowerCase() + " love eating " + txt[1][1].toLowerCase()); // or var txt1 = txt[0][1] + " love eating " + txt[1][1]; document.write(txt1.toLowerCase()); But if I will loop through all the arrays and print them out, I am bothered with appending .toLowerCase(0 after each array one by one, so is there any way to bind that method at one go? I hope my question is understandable. Maybe I've used wrong terms of JS. Thank you. How do you format a if statment for a multidemensional array.
This has been resolved. The moment i posted it i realised the mistake i was making . Learnig how to delete my post, until then thought i would sdimply delete the content.
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 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? 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++; } } Hi again folks! A code I did recently was that 10 football teams had to register and the program had to ask the question "please enter your team" ten times then show the display on screen. This code works fine and does it jobs but I realized that I did this program a long winded way (shown below) : <script type="text/javascript"> //ask to enter names var enteredteam1= prompt("Please enter first team.", ""); //each team is shown as different variable var enteredteam2= prompt("Please enter second team.", ""); var enteredteam3= prompt("Please enter third team.", ""); var enteredteam4= prompt("Please enter forth team.", ""); var enteredteam5= prompt("Please enter fifth team.", ""); var enteredteam6= prompt("Please enter sixth team.", ""); var enteredteam7= prompt("Please enter seventh team.", ""); var enteredteam8= prompt("Please enter eighth team.", ""); var enteredteam9= prompt("Please enter ninth team.", ""); var enteredteam10= prompt("Please enter final team.", ""); var team= []; team[1]= enteredteam1 //the team should equal the entered value for the space team[2]= enteredteam2 team[3]= enteredteam3 team[4]= enteredteam4 team[5]= enteredteam5 team[6]= enteredteam6 team[7]= enteredteam7 team[8]= enteredteam8 team[9]= enteredteam9 team[10]= enteredteam10 document.write("<h1>Registered Teams</h1>"); // display the teams on the screen beside number document.write("<b>1.</b>" + team[1]); //write the entered value on the screen document.write("<br><br><b>2.</b>" + team[2]); document.write("<br><br><b>3.</b>" + team[3]); document.write("<br><br><b>4.</b>" + team[4]); document.write("<br><br><b>5.</b>" + team[5]); document.write("<br><br><b>6.</b>" + team[6]); document.write("<br><br><b>7.</b>" + team[7]); document.write("<br><br><b>8.</b>" + team[8]); document.write("<br><br><b>9.</b>" + team[9]); document.write("<br><br><b>10.</b>" + team[10]); </script> I was wondering for future references could anyone suggest a simpler code to do something similar? For instance what if I wanted to ask the question but I didn't know how many teams were going to be entered. It would ask the question (enter your team) until the user clicked on a button saying "finished" or something. Once again, I am new to this field, so any code with comments would be helpful! |