JavaScript - Looping Through Arrays: For/in Vs Using Array Length
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. 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. /* My array is like so... shp[0][0] = 5; shp[0][1] = "A5"; shp[0][2] = "A2"; shp[0][3] = "A1"; shp[0][4] = "A4"; shp[0][5] = "A3"; shp[1][0] = 4; shp[1][1] = "C3"; shp[1][2] = "C4"; shp[1][3] = "C1"; shp[1][4] = "C2"; shp[2][0] = 3; shp[2][1] = "E1"; shp[2][2] = "E3"; shp[2][3] = "E2"; shp[3][0] = 3; shp[3][1] = "G3"; shp[3][2] = "G2"; shp[3][3] = "G1"; shp[4][0] = 2; shp[4][1] = "I2"; shp[4][2] = "I1"; the results I am after is... shp[0][0] = 5; shp[0][1] = "A1"; shp[0][2] = "A2"; shp[0][3] = "A3"; shp[0][4] = "A4"; shp[0][5] = "A5"; shp[1][0] = 4; shp[1][1] = "C1"; shp[1][2] = "C2"; shp[1][3] = "C3"; shp[1][4] = "C4"; shp[2][0] = 3; shp[2][1] = "E1"; shp[2][2] = "E2"; shp[2][3] = "E3"; shp[3][0] = 3; shp[3][1] = "G1"; shp[3][2] = "G2"; shp[3][3] = "G3"; shp[4][0] = 2; shp[4][1] = "I1"; shp[4][2] = "I2"; so it sorts all from the second part of the array to the end in alpha-numerical order. I tried the following but i get errors about Cannot call method 'unshift' of undefined. // var shp; var shpbk; var shpbktemp; // shpbk = shp.slice(); shpbktemp[0] = shpbk[0][0]; shpbk[0] = shpbk[0].shift; shpbk[0] = shpbk[0].sort; shpbk[0] = shpbk[0].unshift(shpbktemp[0]); shpbktemp[1] = shpbk[1][0]; shpbk[1] = shpbk[1].shift; shpbk[1] = shpbk[1].sort; shpbk[1] = shpbk[1].unshift(shpbktemp[1]); shpbktemp[2] = shpbk[2][0]; shpbk[2] = shpbk[2].shift; shpbk[2] = shpbk[2].sort; shpbk[2] = shpbk[2].unshift(shpbktemp[2]); shpbktemp[3] = shpbk[3][0]; shpbk[3] = shpbk[3].shift; shpbk[3] = shpbk[3].sort; shpbk[3] = shpbk[3].unshift(shpbktemp[3]); shpbktemp[4] = shpbk[4][0]; shpbk[4] = shpbk[4].shift; shpbk[4] = shpbk[4].sort; shpbk[4] = shpbk[4].unshift(shpbktemp[4]); Ok so this is probably a simple question but i have hit a wall he So I have 20 arrays with incremental names (course1, course2, course3 ...) What i want to make is a selection box with 20 options. for each option the value would be course1[0] and the text shown would be course1[1]. if i write this code: <code> for (var i=1; i<=20; i++){ var select = document.getElementById("selectiontest") select.options[select.options.length] = new Option (course1[1], course1[0]) } </code> The code works and the correct array values are put as the option text and value. I am having trouble getting the loop to move from course1 to course2, i used the loop counter in the array name like this: <code> for (var i=1; i<=20; i++){ var select = document.getElementById("selectiontest") select.options[select.options.length] = new Option (('course'+i)[1], ('course'+i)[0]) } </code> this is where it stops working. I get 20 values of o. which i assume is the second character of course. How do i tell javascript to incrementally change the array name during the loop? All, I have the following code: console.log("My num is: " + num); console.log("My lat is: " + lat); console.log("My lat length is: " + lat.length); console.log("My long is: " + long); When I get the output, I get the following: My num is: {"1":1,"2":2} My lat is: {"1":"40.59479899","2":"41.4599860"} My lat length is: 36 My long is: {"1":"-75.5549650","2":"-87.596430"} I'm confused on why the length is saying 36 when it's obviously two and the other output shows that??? Hello, another noob question for you: I have a function that requires the ability to count the number of entries in an array. I'm using the following to call my function inside an input tag: Code: onblur="javascript:check(this.name, this.value, 1, 10);" which for example is calling check('field1', 'foobar', 1, 10) Here is the javascript: Code: function check(name, value, min, max){ var errors=new Array(); if(value.length < min || value.length > max){ //checking against min/max length of value errors[name] = "Text field must not be blank."; errors["blabla"] = "array value 2"; //added for testing purposes alert(name+" : "+value); //returns "field1 : foobar" } alert(errors.length); // returns "0" } And when errors.length is alerted, it outputs 0. I can only figure that there is an issue when using custom named keys in an array, since this works when I use only integers, however, I have the need to use a custom key index as shown. Any ideas? Hi, I'm banging my head off a brick wall with setting up a 3 dimensional array and trying to loop through it. I'm using the EJS framework (http://embeddedjs.com/). We currently have a 2D array set up to list out features. See below: topfeatures: [ "Feature 1", "Feature 2", "Feature 3", "Feature 4", "Feature 5", "Feature 6" ] <ul> [% for(var i = 0; i < this.topfeatures.length; i++) { %] <li>[%= this.topfeatures[i] %]</li> [% } %] </ul> However, the request we have requires headlines for each set of features. Headline 1 Feature1 Feature2 Feature3 Headline 2 Feature4 Feature5 Feature6 Any ideas how I can do this? Code: <SCRIPT LANGUAGE = "JAVASCRIPT"> 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]; //code to declare a new array to store the combined points for each couple var combinedPointsArray=new Array(); //code to calculate the combined points for each couple and store it in the combined points array for (i = 0; i <= 4; i++) { combinedPointsArray[i] = judgesPointsArray[i] + audiencePointsArray[i]; //code to find and output the maximum value in the combined points array } var winner = [0]; //set first pair as default winner for (i = 1; i <= 4; i++) { //start with second pair if (combinedPointsArray[i] => combinedPointsArray[winner[0]]) { //compare to first in the winners winners = [i]; //new high score }else if (combinedPointsArray[winner] == combinedPointsArray[i]) { winners[winners.length] = i;//add to highest tie } //danceoff between all numbers in winner array }//for for(i=0;i<winners.length;i++){ document.write(winners[i]+", "); document.write(i); } </SCRIPT> I am having trouble with this program, I cant seem to figure out why this is not working. Basically i need it to loop though the array and find who has the highest points / if more than one have the same points so i dance off is required. Can someone please lend a hand driving me mad. Regards, 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 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? 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! 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] 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. Overview: Order entry project. I am using an iFrame to pull external forms that I can not change. Once our employee enters in the information and submits I would like to redirect the existing window to a new page. I've tried many variations of: Code: <script type='text/javascript'> function iHistory() { var hist=history.length; if (hist>1) { parent.window.location = "orderentry.php"; } } </script> Since I have no control of the external form I have been using OnLoad() in the iFrame tag to call iHistory(). The script works great unless the browser history is >1 If possible, I would like to also setup like a 5 or 10 second delay so the employee can see the framed confirmation page before redirect. So the function needs to check current history.length, when that changes delay 5-10 seconds and redirect parent window to orderentry.php Hello. I wonder is there any javascript to calculate IP length For example I have Start ADDR: VLAN_ADDR which is: 10.52.28.0 Stop ADDR: VLAN_LAST which is 10.52.29.254 As I know:result is 512 or another example: Start ADDR: VLAN_ADDR which is: 10.52.64.11 Stop ADDR: VLAN_LAST which is 10.52.64.15 As I know:result is 5 How to count it in javascript code ? Results are "numbers" Best regards Leos. For some reason i'm getting the error of "length is null". Which is from this . Code: function display_form(id) { //Create some variables var html = ""; var container = "form_container"; var menu = load_menu(id, false); //Get id for ( var i = 0; i < menu.length; i++ ) { alert(i); } http = getHTTPObject(); http.onreadystatechange = function() { if ( http.readyState == 4 && http.status == 200 ) { document.getElementById(container).innerHTML = http.responseText; } else { document.getElemenyById(container).innerHTML = "Loading..."; } } http.open( "GET", "includes/forms.php?form=" + id ); http.send(); //Watch input fields //login_listener(); }/* Here is the function: Code: function load_menu(menu, return_d) { //Availible menus var data = []; data [ 'login' ] = [ 'Login', 'Register', 'Recovery' ]; data [ 'settings' ] = [ 'Profile', 'Account', 'something' ]; if (return_d == false) { return data[ menu ]; } else { //Menu container ID's var cons = Array('menuitem1','menuitem2','menuitem3'); for ( var i = 0; i < cons.length; i++ ) { document.getElementById(cons[i]).innerHTML += data[ menu ] [ i ]; } } } Extra info: id = login menu = login function checkValidFormInput() { if (document.getElementsByName('customerName').value != '') { document.getElementById('customerNameImg').innerHTML = '<img alt="Valid" src="images/greenTick.png">'; } else { document.getElementById('customerNameImg').innerHTML = '<img alt="Invalid" src="images/redX.png">'; } if (document.getElementsByName('customerEmail').length > 0) { document.getElementById('customerEmailImg').innerHTML = '<img alt="Valid" src="images/greenTick.png">'; } else { document.getElementById('customerEmailImg').innerHTML = '<img alt="Invalid" src="images/redX.png">'; } } Ok I have a textarea field that is validated by Js, this textarea can and will contain the newline character Code: \n so I validate in JS Code: if(textareaname.value.length < 200) this hten goes through to my php where i also check before I place in to the Database using MYSQL Code: if( strlen($_POST['textareaname']) < 200 ) but my php is giving me a different string length from my javascript. It looks as if Javascript is counting a newline as 1 character and php is treating it as 2. I have checked my slashes, I have used various REgex to check these data amounts. I have also Googled around and there doesnt seem much around. Any ideas? Any suggestions as to how I can make php and javascript treat a newline as the same amount of characters? Thanks in advance. I want to use the new keyword to instantiate an object. The catch is I want to pass in variable length arguments. Given: Code: function Foo () { this.args = Array.prototype.join.call (arguments); } var args = ["arg0", "arg1", "arg2"]; The following don't work (though I understand why): Code: new Foo.apply (null, args); new (Foo.apply (null, args)); (new Foo).apply (null, args); Any ideas on how to do what I want without modifying Foo's source code? Hi, I have added an validation script for Pizza menu. Validation working fine in all browsers except IE. When I working in IE8 it throws an error "length is null or not an object error in IE8". Please help me. See Java script code below: <script> function UnCheckRadios(radioButtonGroupName) { var formName = "frmOrder"; var form = document.forms[formName]; alert(form); var noOfRadioButtons=form[radioButtonGroupName].length; for(var x=0;x<noOfRadioButtons;x++) { chk=form[radioButtonGroupName] .checked=false; } } </script> PHP code: <input type="radio" id="<?=$subitem['subgroup_id'];?>_comboleft" name="<?=$subitem['subgroup_id'];?>_comboleft" value="<?=$subitem['id'];?>:Left Side" onclick="UnCheckRadios('<?=$subitem["subgroup_id"];?>_combowhole');"> I'm trying to figure out how to add a length paramater to this function. Not quite sure how to do it. here's what I tried: Code: var phone = document.getElementById('phone'); if(isNumericdashes(phone, "Please enter a valid phone number")){ return true; } function isNumericdashes(elem, helperMsg){ var numericExpression = /^[0-9\(\)-]+$/; if(elem.value.match(numericExpression) &&(elem.length > 9)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } |