JavaScript - Help Declaring/using Array Of Arrays
Hi
I need a bit of javascript help with an array please. just don't seem to have the correct syntax. (the "code" below is pseudo code, just to get the idea across) Here's what I currently have: var bill = new array[20]; var sam = new array[20]; var nancy = new array[20]; var Oscar = new array[20]; I'm assigning objects to them (ie Oscar[5] = new objLabel() This seems like a kluge, however. Here's what I'd like (again, pseudo-code) var Objects = {bill:null; sam:null; nancy:null; Oscar:null}; var theObject = new Array of Objects[20]; // yes: i know that's wrong... and that's the part I'm having trouble with so that I can do something like: with theObject[5] do { bill = new objLabel(); nancy = new objImage(); }; Just seems to me that keeping a single array of multiple objects is likely to be less error-prone than multiple arrays of single objects... But I don't have the syntax right... or can it be done in JS? If it's doable, would someone be kind enough to show me how to declare and access that example? Similar TutorialsI 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. /* 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 I apologize in advance for my ignorance. I'm relatively new to javascript. I am trying to dynamically create a page based on information in a .txt. So far the code works. But only for a spacific line in the .txt. I would like it to create numbered divs and fill with approprate info from .txt for each line in .txt. Does that make sense? Any help you can provide would be greatly appriciated. Oh and I'm not worried about cross browser function this is for intra-net and all clients use Mozilla. P.S.: I will paste full code if necessary and it is explained exactly how. Is it: [ "my code goes here" ] or [code] my code goes here [code] Hello there, I was having some trouble with 2D arrays (or array of arrays). Essentially, the array has 100 rows, with two columns. The first column of every row holds a name, and the second holds a sales amount. With the use of a do while loop, the user can continuously add up to 100 names and sales amounts. After all the information the user wishes to add is stored into the 2D array I'm attempting to pass that very same 2D array as a parameter to a function called printRow as can be seen in the code below: Note: the function call and the actual function are found in two separate javascripts. Code: var salesPerson=new Array(100) for (i=0; i <=100; i++) { salesPerson[i]=new Array(2); } var x = 0; do { salesPerson[x][0] = getName(); salesPerson[x][1] = getSales(); x++; }while(x != 100 && confirm("Enter more employee information?")); printRow(salesPerson[][]); Code: function getName() { var nameEntered = prompt("What is your first name?"); return nameEntered; } function getSales() { var error; var salesEntered; do { salesEntered = prompt("What were your sales?"); error = false; if (isNaN(salesEntered) || salesEntered == null || salesEntered == "") error = true; }while(error); return salesEntered; } function printRow(salesPerson[][]) { for (i =0; i<salesPerson.length; i++) { document.write(salesPerson[i][0] + " " + salesPerson[i][1]); } } At the moment I'm only looking to print the contents of the 2D array that I pass as a parameter to the document. As is, the javascipt doesn't seem to execute at all, it worked fine up until I added the printRow function call and function which leads me to believe I may not be passing it as a parameter correctly. Any tips on how to do this correctly would be greatly appreciated! Hi, I'm a JS beginner and I find looping through arrays with for/in is very easy. Yet I find lots of code examples where array length is used instead of for/in and I'm thinking to myself, why do it this (somewhat) hard(er) way? Maybe I'm missing something... Thanks for your help. I was looking at that old Strawberry Fields problem and I thought I'd see about solving it in JavaScript. What I want is an array of chars so that I can set individual elements in the array of arrays. Strings are apparently immutable and can't directly be changed? Here's my code. Code: var field = new Array(); var string0 = "..@@@@@..............." var string1 = "..@@@@@@........@@@..." var string2 = ".....@@@@@......@@@..." var string3 = ".......@@@@@@@@@@@@..." var string4 = ".........@@@@@........" var string5 = ".........@@@@@........" for (var i = 0; i < 6; i++) { field[i] = new Array(); field[i] = eval("string" + i + ".slice('')"); } document.write("field's type is " + typeof field + "<br>"); // object? but it should be explicit array document.write(typeof field[1]) // string? it should explicitly be an array, then it was filled with array elements document.write(typeof field[1][2]); // string - ok, I understand this bit document.write(field[1].length); document.write("<br>"); for (var i = 0; i < field.length; i++) { field[i] = new Array(); for (var k = 0; k < eval("string" + i + ".length"); k++) { field[i][k] = eval("string" + i + ".charAt(" + k + ")"); } document.write("<br>"); } document.write("field's type is " + typeof field + "<br>"); // seriously, an object? document.write(typeof field[1]) // why is this an object instead of an array? document.write(typeof field[1][2]); // string, yeah, I understand this as well document.write(field[1].length); document.write("<br>"); Also, it looks like I can't overwrite a 1-length string that's in the array of arrays. For instance: Code: newField = field; //for loops newField[i][k] = 0; // does nothing, newField's elements remain the same. Today I have been embedding some Google Maps on my website. When I got around to putting in event handlers for markers on the map I ran into some trouble with how to declare them in the way I have the map setup. The issue is that I have an array, label, and want to indicate a single element from that array to the event handling function. But the declaration of this seems tricky. The code in question are the two lines like this one in the script below: GEvent.addListener(marker[i], 'mouseover', function() { map.addOverlay(label[i]); }); Specifically, the problem is with function() { map.addOverlay(label[i]); because I don't want label[i] to be used, but whatever value i has should be substituded in there. But since this is a function being declared and not actually executed the value for i does not get used. I've been able to get it to work by using eval() to force the actual value of i into the code, like so: eval('GEvent.addListener(marker[i], \'mouseout\', function() { map.removeOverlay(label['+i+']); });'); but am wondering if there is a better solution? Here's a section of my script showing the issue in context. You can see that i is incremented with a loop and used as the index of a few arrays. Code: for (i = 0; i < buildings.length; i++) { icon[i] = new GIcon(); icon[i].image = 'http://labs.google.com/ridefinder/images/mm_20_red.png'; icon[i].iconSize = new GSize(12, 20); icon[i].iconAnchor = new GPoint(6, 20); map.addOverlay(marker[i] = new GMarker(new GLatLng(buildings[i][1], buildings[i][2]), {icon:icon[i]})); label[i] = new ELabel(new GLatLng(buildings[i][1], buildings[i][2]), '<nobr>'+buildings[i][3]+'<\/nobr>', 'maplabel'); GEvent.addListener(marker[i], 'mouseover', function() { map.addOverlay(label[i]); }); GEvent.addListener(marker[i], 'mouseout', function() { map.removeOverlay(label[i]); }); } Hi all, Rookie (extremely) programmer here, so be gentle Trying to build a little tool here.. Code: <html> <body> Artist ID: <input type=TEXT id=ArtistID name= ArtistID value="Artist ID"> <SELECT> <OPTION value="http://URL.com/EditUser/"ArtistID.value".html">Edit User</OPTION> <OPTION value="http://URL.com/EditArtist/"ArtistID.value".html">Edit Artist</OPTION> <OPTION value="http://URL.com/Subscruptions/"ArtistID.value".html">Subscriptions</OPTION> <OPTION value="http://URL.com/ControlRoom/"ArtistID.value".html">Control Room</OPTION> </SELECT> <input type="submit" value="Chyeah"> </body> </html> Yeah. Like I said. Rookie. I'm trying to save the input and pass it into the URLs that are the option values. So Artist ID being 111 would take you to url.com/<WHATEVER OPTION YOU CHOSE FROM DROP DOWN>/111 What am I doing wrong/What am I not doing? ps if this is in the wrong forum, sorry! Feel free to move it. Couldn't decide if this should go in DOM forum or not (probably bc I don't know what DOM is!) Hi all, I'm a javascript newbie and having some trouble with what I imagine it s a very basic issue! I am trying to declare a variable inside a function and use it later on in my code... but it just already returns white space... i.e. not variable value. I am setting it within this function: Code: function show_video1(){ document.getElementById('video1').style.display="block"; var video1Name = "Education World News (Part 1)"; document.getElementById('video2').style.display="none"; document.getElementById('video3').style.display="none"; document.getElementById('video4').style.display="none"; document.getElementById('video5').style.display="none"; document.getElementById('video6').style.display="none"; document.getElementById('video7').style.display="none"; document.getElementById('video8').style.display="none"; document.getElementById('video9').style.display="none"; document.getElementById('video10').style.display="none"; document.getElementById('video11').style.display="none"; } and trying to call it later on with this: Code: <script type="text/javascript">document.write(video1Name)</script> It might be worth noting that each one of my 11 videos will hace a different name. Can anyone help out a newbie? Many thanks, greens85 Hey guys, i'm taking on my first minor project in javascript and i've run into an error. For whatever reason, buttons i've defined are calling on functions that supposedly don't exist, yet they are clearly in the code and can be applied anywhere. I also checked the syntax errors in google chrome and they state: Uncaught SyntaxError: Unexpected token else Uncaught reference error: go() is not defined Uncaught reference error: highscore() is not defined. So without further delay, here is the full code. Can anyone help me out? Code: <html> <head> <script type="text/JavaScript"> <!-- var sam = 9; var sally = 8; var donald = 4; function percentage (score) { return score / 10 * 100; }; function go() { document.write("Sam's score on the test is " + percentage(sam) + "%, <br \> Sally's score on the test is " + percentage(sally) + "%, <br \> Donald's score on the test is " + percentage(donald) + "%"); }; function highscore() { if (Math.max(90, 80, 40) === 90){ document.write("Sam's score was the highest.")}; else if (Math.max(90, 80, 40) === 80){ document.write("Sally's score was the highest.")}; else{ document.write("Donald's score was the highest.")} }; //--> </script> </head> <body> <input type="button" onclick="go()" value="Student Grades"> <br \> <input type="button" onclick="highscore()" value="Highest Score"> </body> </html> Hi, I am doing a Validation for Form "Text input". If the user leaves the input empty, a function is starting to run. If the field is bigger than 1 - so it doesn't get into the function. The problem is: The first time, the user left the input empty, function ran, and I got the alert - that's OK. Second time, The user added 10 in the AGE input - And again he gets the Alert - But he should not. Note: Age input value, returns from a different function (calc) to a var called: result. this is the code: Code: $(document).ready(function(){ $('#btn_send').click(function(){ //var result gets the value from another function of input "Age" value. -> return thisform.Age.value var result = calc(document.getElementById("campaignform")); if (result<1) { $("#campaignform").submit(function(event) { event.preventDefault(); alert ("prevent default"); }); } else{ return true; }; }); }); so if you try the second time to click on Submit, then you get into $('#btn_send').click(function() and eventhough you added for example 67 in the AGE (return as result) input, you get into the IF statement which is: if (result<1) I'm pretty new to developing, so I hop you will understand me. Sorry if I have mistakes. Can you advice what could be a better TITLE for this question? thanks in advance, Shai 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. 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. OK first of all I will post some screenshots of the 'website' I have created so far and explain what is working and what is not working. Then I will post my code and ask for help. Below is the main screen before any action happens. The three boxes are DIV elements. The writing and dropdown menu in the first box is generated by Javascript code. Whenever a user selects an option from the dropdown menu. Information about the movie and a picture of the cover are displayed. The movie title, picture filename and movie description are all stored in three separate arrays. Now for the problem. I have created a fourth array "customerList" and left it empty. Whenever a customer clicks the reserve button it calls a function "myReserve()". This function takes the selection from the dropdown menu, then uses the push function to add the selection to the blank array. I then use the code "arrayLength = customerList.length" to get the length of the customer list. A for loop is used to cycle through the array and display the contents of the array. The problem is it only displays one selection. When reserve is clicked again the newest selection is displayed. Why will it not push the next item into the array? Javascript code, just skip through the 3 arrays at the top... the problem function is at the bottom. Code: var movieTitles = new Array(8) movieTitles[0] = "The Prestige [2006]" movieTitles[1] = "The Lives of Others [2007]" movieTitles[2] = "The Bourne Ultimatum [2007]" movieTitles[3] = "Spider-Man 3 [2007]" movieTitles[4] = "Casino Royale [2006]" movieTitles[5] = "The Illusionist [2006]" movieTitles[6] = "Sunshine [2007]" movieTitles[7] = "Zodiac [2007]" movieTitles[8] = "Quantum of Solace [2008]" var movieCovers = new Array(8) movieCovers[0] = "prestige.jpg" movieCovers[1] = "lives_of_others.jpg" movieCovers[2] = "bourne3.jpg" movieCovers[3] = "spiderman3.jpg" movieCovers[4] = "casinoroyal.jpg" movieCovers[5] = "illusionist.jpg" movieCovers[6] = "sunshine.jpg" movieCovers[7] = "zodiac.jpg" movieCovers[8] = "quantum_of_solace.jpg" var movieDescriptions = new Array(8) movieDescriptions[0] = "Two Victorian-era magicians develop a rivalry that builds into an escalating battle of tricks." movieDescriptions[1] = "Five years before its downfall, the former East-German government ensured its claim to power with a ruthless system of control and surveillance." movieDescriptions[2] = "Legendary assassin Jason Bourne uncovers mysteries of his past, which puts him in the cross-hairs of a superkiller." movieDescriptions[3] = "When Peter Parker's suit suddenly turns black it brings out the dark, vengeful side of his personality." movieDescriptions[4] = "The story examines James Bond's first mission after getting his licence to kill." movieDescriptions[5] = "Eisenheim is a stage magician who amazes the audiences of turn-of-the-century Vienna, drawing the attention of Crown Prince Leopold." movieDescriptions[6] = "Fifty years from now, the sun is dying, and mankind is dying with it. Our last hope: a spaceship carrying a device which will breathe new life into the star." movieDescriptions[7] = "A serial killer terrifies the San Francisco Bay Area and taunts police with his ciphers and letters." movieDescriptions[8] = "Seeking revenge for the death of his love, secret agent James Bond sets out to stop an environmentalist from taking control of a country's water supply." var customerList = new Array() function getMovieTitle() { var str = "<p>Available movies are contained in the list below.<br />Select a movie title to read more details.<br />If you want to add the movie to your list click the reserve option.<br /></p>" str = str + "<form action='P4_1.html' method='post'><select onChange = 'displayMovie()' name='title' id = 'droplist'><option>Choose a movie</option>" mylength = movieTitles.length //loop for each movie title in the movieTitles array for (var i=0; i<mylength; i++) { str = str + "<option>" + movieTitles[i] + "</option>" } str = str+"</select></form>" //place content into dropdown menu document.getElementById("dropdown").innerHTML = str } function displayMovie() { var i i = document.getElementById('droplist').selectedIndex - 1 var m = movieTitles[i] m = m + "<p><br><img src='"+movieCovers[i]+"'></p>" m = m + movieDescriptions[i] m = m + "<p> <a href='Javascript:myReserve()'><span id = 'res'> Reserve </span></a></p>" document.getElementById("Movie_Info").innerHTML = m } function myReserve() { var i i = document.getElementById('droplist').selectedIndex - 1 customerList.push(movieTitles[i]) arrayLength = customerList.length for (var j=0; j<arrayLength; j++) { str = customerList[j] } document.getElementById("Movie_List").innerHTML = str } HTML code, incase you want to create my files yourself to troubleshoot for me but all the problems occur in the myReserve function just above. Everything else works fine. Code: <html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"> <head> <title>P4_1</title> <script src="P4.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" media="screen" href="P4.css" /> <!--[if gte mso 9]><xml> <mso:CustomDocumentProperties> <mso:ContentType msdt:dt="string">Document</mso:ContentType> </mso:CustomDocumentProperties> </xml><![endif]--> </head> <body onload="javascript:getMovieTitle()"> <img src="logo.jpg"> <div id="dropdown" class="box1"> </div> <div id="Movie_Info" class="box2"> <p>Movie info will go here</p> </div> <div id="Movie_List" class="box3"> <p>Your movie list will go here</p> </div> </body> </html> Hey, I'm working on a problem and what I need the program to do is to add up the numbers in the array NOT add up how many numbers there are. There are 5 total numbers that a user will input. The counting of the numbers will be in a seperate method which will then return to the main. Then be displayed through system.out.println. I don't know where I am going wrong any help? Thanks! Code: import javax.swing.*; import java.util.*; public class Question10 { public static void main (String []args) { //declares Scanner keyboard = new Scanner(System.in); int [] myNums = new int[5]; for (int i=0; i < myNums.length; i++) { System.out.println ("Please Enter Data"); myNums[i]= keyboard.nextInt(); } } //end main public static int getTotal(int inArray) { int a,b,c,d,e,f; f = a+b+c+d+e; return f; } }//end class 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. |