Jump to content

Loops Making Me Go Loopy


chibineku

Recommended Posts

One of the exercises in the JavaScript Bible was to add a for loop to a function so that it could count the instances of the letter 'e' in a user-entered string. Piece of cake.So, I thought, why don't I see if I can make a function that counts all instances of every letter in the alphabet. I decided to assign the letters as a string to a variable, and loop through the user entered string, for as many letters as there are in said string. Each letter of the string would be compared, in another loop, to the letters of aphabet, one at a time. To store the result, I want to modify a variable (a 26 space string) so that in the position in that string corresponding to the letter of the alphabet (the number at position 0 would be the number of letter A's), I would have a number I could extract later and assign to a variable. It all sounds comfusing. Here's the code:

<html><head><title>AlphaCount</title><script type="text/javascript">function countLetters(form) {var count=0var alphabet="abcdefghijklmnopqrstuvwxyz"var alphaCount="						  "var inputString=form.mainstring.value.toLowerCase();for (i=0;i<inputString.length;i++) {for (ii=0;ii<alphabet.length;ii++) {if (inputString.charAt(i)==alphabet.charAt(ii)){count++alphaCount.charAt(ii)=count}}count=0}var a=alphaCount.charAt(0)var b=alphaCount.charAt(1)var c=alphaCount.charAt(2)var d=alphaCount.charAt(3)var e=alphaCount.charAt(4)var f=alphaCount.charAt(5)var g=alphaCount.charAt(6)var h=alphaCount.charAt(7)var i=alphaCount.charAt(8)var j=alphaCount.charAt(9)var k=alphaCount.charAt(10)var l=alphaCount.charAt(11)var m=alphaCount.charAt(12)var n=alphaCount.charAt(13)var o=alphaCount.charAt(14)var p=alphaCount.charAt(15)var q=alphaCount.charAt(16)var r=alphaCount.charAt(17)var s=alphaCount.charAt(18)var t=alphaCount.charAt(19)var u=alphaCount.charAt(20)var v=alphaCount.charAt(21)var w=alphaCount.charAt(22)var x=alphaCount.charAt(23)var y=alphaCount.charAt(24)var z=alphaCount.charAt(25)msg=a+" instances of the letter a, "+b+" instances of the letter b, "msg+=c+" instances of the letter c, "+d+" instances of the letter d, "msg+=e+" instances of the letter e, "+f+" instances of the letter f, "msg+=g+" instances of the letter g, "+h+" instances of the letter h, "msg+=i+" instances of the letter i, "+j+" instances of the letter j, "msg+=k+" instances of the letter k, "+l+" instances of the letter l, "msg+=m+" instances of the letter m, "+n+" instances of the letter n, "msg+=o+" instances of the letter o, "+p+" instances of the letter p, "msg+=q+" instances of the letter q, "+r+" instances of the letter r, "msg+=s+" instances of the letter s, "+t+" instances of the letter t, "msg+=u+" instances of the letter u, "+v+" instances of the letter v, "msg+=w+" instances of the letter w, "+x+" instances of the letter x, "msg+=y+" instances of the letter y, "+z+" instances of the letter z."alert("Your string had: "+msg)}</script></head><body><form>Enter any string: <input type="text" name="mainstring" size="30" ?><br /><input type="button" value="Count the instances of each letter of the alphabet" onclick="countLetters(this.form)" /></form></body></html>

The problem is this line:

alphaCount.charAt(ii)=count

It won't work. Firefox error console says: Invalid assignment left-hand-side. I don't want to cheat and search for anyone else's solution to this, but can anyone suggest a reason that this variable modification doesn't work? I tried: alphaCount.charAt(ii)=ii as well, but same problem. 'ii' isn't a reserved object, is it? I know 'i' is a standard counting variable for if loops, so I just thought it made sense using 'ii'.

Link to comment
Share on other sites

One of the exercises in the JavaScript Bible was to add a for loop to a function so that it could count the instances of the letter 'e' in a user-entered string. Piece of cake.So, I thought, why don't I see if I can make a function that counts all instances of every letter in the alphabet. I decided to assign the letters as a string to a variable, and loop through the user entered string, for as many letters as there are in said string. Each letter of the string would be compared, in another loop, to the letters of aphabet, one at a time. To store the result, I want to modify a variable (a 26 space string) so that in the position in that string corresponding to the letter of the alphabet (the number at position 0 would be the number of letter A's), I would have a number I could extract later and assign to a variable. It all sounds comfusing. Here's the code:
<html><head><title>AlphaCount</title><script type="text/javascript">function countLetters(form) {var count=0var alphabet="abcdefghijklmnopqrstuvwxyz"var alphaCount="						  "var inputString=form.mainstring.value.toLowerCase();for (i=0;i<inputString.length;i++) {for (ii=0;ii<alphabet.length;ii++) {if (inputString.charAt(i)==alphabet.charAt(ii)){count++alphaCount.charAt(ii)=count}}count=0}var a=alphaCount.charAt(0)var b=alphaCount.charAt(1)var c=alphaCount.charAt(2)var d=alphaCount.charAt(3)var e=alphaCount.charAt(4)var f=alphaCount.charAt(5)var g=alphaCount.charAt(6)var h=alphaCount.charAt(7)var i=alphaCount.charAt(8)var j=alphaCount.charAt(9)var k=alphaCount.charAt(10)var l=alphaCount.charAt(11)var m=alphaCount.charAt(12)var n=alphaCount.charAt(13)var o=alphaCount.charAt(14)var p=alphaCount.charAt(15)var q=alphaCount.charAt(16)var r=alphaCount.charAt(17)var s=alphaCount.charAt(18)var t=alphaCount.charAt(19)var u=alphaCount.charAt(20)var v=alphaCount.charAt(21)var w=alphaCount.charAt(22)var x=alphaCount.charAt(23)var y=alphaCount.charAt(24)var z=alphaCount.charAt(25)msg=a+" instances of the letter a, "+b+" instances of the letter b, "msg+=c+" instances of the letter c, "+d+" instances of the letter d, "msg+=e+" instances of the letter e, "+f+" instances of the letter f, "msg+=g+" instances of the letter g, "+h+" instances of the letter h, "msg+=i+" instances of the letter i, "+j+" instances of the letter j, "msg+=k+" instances of the letter k, "+l+" instances of the letter l, "msg+=m+" instances of the letter m, "+n+" instances of the letter n, "msg+=o+" instances of the letter o, "+p+" instances of the letter p, "msg+=q+" instances of the letter q, "+r+" instances of the letter r, "msg+=s+" instances of the letter s, "+t+" instances of the letter t, "msg+=u+" instances of the letter u, "+v+" instances of the letter v, "msg+=w+" instances of the letter w, "+x+" instances of the letter x, "msg+=y+" instances of the letter y, "+z+" instances of the letter z."alert("Your string had: "+msg)}</script></head><body><form>Enter any string: <input type="text" name="mainstring" size="30" ?><br /><input type="button" value="Count the instances of each letter of the alphabet" onclick="countLetters(this.form)" /></form></body></html>

The problem is this line:

alphaCount.charAt(ii)=count

It won't work. Firefox error console says: Invalid assignment left-hand-side. I don't want to cheat and search for anyone else's solution to this, but can anyone suggest a reason that this variable modification doesn't work? I tried: alphaCount.charAt(ii)=ii as well, but same problem. 'ii' isn't a reserved object, is it? I know 'i' is a standard counting variable for if loops, so I just thought it made sense using 'ii'.

charAt() is a read-only function. It just returns the character that's located at a certain position.
Link to comment
Share on other sites

charAt() is a read-only function. It just returns the character that's located at a certain position.
Ah. It's obviously only an exercise and not really important, and I can think of one or two really longwinded ways of doing it, but can you think of anything off the top of your head that would do what I want? It seems like a shortcoming, somehow, since the ways of reading parts of strings seems quite comprehensive.
Link to comment
Share on other sites

What is missing is a string.splice function. You can add one like this:String.prototype.splice=function(i,r,s){s=s||""; return this.substr(0,i) + s + this.substr(i+r) };use it like this:var str = "1234567890";var newstr1 = str.splice(3, 0, "TEST");// returns "123TEST4567890";var newstr2 = str.splice(3, 1, "H");//returns "123H567890";

Link to comment
Share on other sites

To give a hint: strings are arrays.This program will do what you're trying with your code, highlight it with your mouse if you want to see the solution.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <title>Title</title> <script type="text/javascript"> function countLetters(s,el) { // Make a list of letters var letters = "abcdefghijklmnopqrstuvwxyz"; // Start the string we'll be appending the results to var result = ""; // declare some variables we'll be using later on var n, j; // Loop through all the letters of the alphabet for(var i=0; i<letters.length; i++) { // reset the counter n = 0; for(j = 0; j < s.length; j++) { // Add 1 to n if the letter of position j in the string is equal to the current letter being evaluated if(s[j] == letters) n++; } // Just for gramatically correct output, check for cases n = 1 and n = 0 if(n == 1) { result += "There is " + n + " instance of letter " + letters + "<br>"; } else if(n == 0) { result += "There are no instances of letter " + letters + "<br>"; } else { result += "There are " + n + " instances of letter " + letters + "<br>"; } } // Display the result in the element 'el' el.innerHTML = result; } </script> </head> <body> <div> <input type="text" value="The quick brown fox jumps over the lazy dog" id="str" style="width: 300px;"> <input type="button" value="Count letters" onclick="countLetters(document.getElementById('str').value,document.getElementById('r'))"> <div id="r"></div> </div> </body></html>

Link to comment
Share on other sites

You're sort of on the right path with your original script, but there are some changes you can make to make it a little more efficient. For example, instead of comparing the character with every letter in the alphabet, just keep a list of characters that have been found and increment the counter each time you find another one. You don't need to check which character it is, you just increment the counter for whichever one it is. You can use an array or generic object to keep track of that.

var found_chars = new Object();var inputString=form.mainstring.value.toLowerCase();var c;for (i=0;i<inputString.length;i++) {  // get the character  c = inputString.charAt(i);    // check if it's been found before  if ((typeof found_chars[c]) == "undefined")  {	// add it and set the count to 1	found_chars[c] = 1;  }  else  {	// increment the counter for it	found_chars[c]++;  }}for (var x in found_chars){  alert("Character \"" + x + "\" occurred " + found_chars[x] + " times.");}

After the loop, if you want to check for a certain character you can do so. found_chars["e"] would tell you how many e's it found, found_chars[" "] would tell you how many spaces, etc.

Link to comment
Share on other sites

What is missing is a string.splice function. You can add one like this:String.prototype.splice=function(i,r,s){s=s||""; return this.substr(0,i) + s + this.substr(i+r) };use it like this:var str = "1234567890";var newstr1 = str.splice(3, 0, "TEST");// returns "123TEST4567890";var newstr2 = str.splice(3, 1, "H");//returns "123H567890";
That is way over my head at the moment! I have got it to work, but I can't pretend to understand quite why. I am sure my JS Bible will fill me in in due course, but for now, many thanks :) If you ever feel like givig a bit of an account, that would be most appreciated, however.Ingolme: Thanks for the clue! I will have a think about it.justsomeguy: That looks like a pretty elegant solution. I will try it with your fix, and I will try Ingolme's as well. I am constantly impressed with the level of help given on this forum.
Link to comment
Share on other sites

Ingolme: I cheated and checked your solution. That's so much easier than what I was trying to do, and very elegant. I altered the else if (n==) condition so that no additional output is added to the result, which makes it look really tidy. The exciting thing about programming is that no matter how simple the task, there are a dozen different approaches, and it's going to take a while before I start hitting on the right solution first time, and before I know when to cut my losses and try a different way.Once again, thanks for the input - to everyone who has posted here and on my other threads. :)

Link to comment
Share on other sites

If you ever feel like giving a bit of an account . . .
Oh. You want to understand stuff. Obviously not one of our high school students. :) I'll print out the method assignment more conventionally:
String.prototype.splice = function (i, r, s) {	 s = s || "";	 var new_string = this.substr(0, i) + s + this.substr(i + r);	 return new_string; };

In line 1 we are actually modifying the JavaScript String object. Every string is a String object, which is why every string has access to properties like .length and methods like .split() . By tinkering with the prototype property, we can actually add properties and methods to the String's object definition. So any changes we make will apply to ALL strings in the script. (Don't worry. We are not changing people's browsers for all time. Only the strings in our script.)So what we are doing is adding a method, called .splice(), to the String object. A method needs a function definition, so that explains the rest of line 1. Just so you'll know, I modeled this after the array.splice() method, so i refers to the index where we will put any insertions that get passed; r refers to the number of replacements we want to make; and s refers to any string we plan to insert.In line 2 we handle a problem that would occur if we chose not to pass any strings to the method. In such a case, s would be undefined, and the word "undefined" would be substituted for its value in line 3. We wouldn't want that. So we are saying this: "If s gets assigned a value when the method is called, let s equal itself. If it doesn't have a value (this is where the 'or' operator ( || ) comes in), let its value be an empty string." This is a really sweet use of the || operator, by the way, and it has many applications. Seasoned programmers use it all the time, and it's a pity more languages don't allow it.In line 3, we build the return string. this is a JavaScript keyword that refers (in this case) to the string itself. So this.substr() returns a substring of the original string. In the first call, we are grabbing that part of the original between the 0th character and the index character. You know what s is. In the second call to .substr(), we are grabbing that part of the original string between the index and the end of the string. Since we are going to the end of the string, we don't need to pass a length parameter. All we're passing is an index.A slight wrinkle. We might not want a simple insertion. We might want an insertion and replacement. The variable r tells the method how many characters to delete from the original. So passing i + r to .substr() tells .substr() to return that part of the string that begins at i characters plus r characters. If r = 0, then it's a simple insertion. If r has a positive value, then we will effectively be deleting r characters after the index.The ability to re-prototype JavaScript objects comes in handy as you create more and more complicated web applications, and it is one of the features of the language that makes it more sophisticated than an old-fashioned scripting language, like BASIC.Note: To be really clever, we should see if the scripting environment already has a .splice method before we go assigning one. (You never know what will happen in the future.) A simple test will do:if (!String.prototype.splice) {//add our method}

Link to comment
Share on other sites

Thanks very much, (Deirdre's) Dad. I was especially discombobulated by the or operator, since I've not come across that before. The whole thing makes a heck of a lot more sense. I am intrigued by the possibilities of this function. Say I had an xml file which contains a databse of film reviews, with nodes called, say, <title>, <content>, <rating>, etc. If I call that xml in a script, would an xsl file referenced in the XML page format it, or does JS merely recognize it as a series of strings? If the latter is true, could I insert into the <content> tags some unique character that I can find using a function, like the string replacement one you just explained, and replace it with some html tags? For example:<CONTENT>Hi, my name is ~Jonathon#</CONTENT>Could I find the '~' and replace it with <span class="name"> and replace '#' for </span>? I am not too set on the idea of using xml to store all the content for a site, but for something that is going to be archived it might be a neat solution.Anyway, thanks again for the very detailed explanation. I am swimming in new information lately, and I'm afraid I'll forget most of it.

Link to comment
Share on other sites

You can TOTALLY use XML to store data. You can grab an XML file from your server using AJAX, and you don't have to parse it into strings. Just use DOM properties/methods to access data. That is their origin in the first place, as ways to traverse and access XML nodes. This is a common technique. The X in AJAX in for XML, though AJAX is not limited to XML files.But, yes, once you have the text data from a node, you can use a lot of methods to replace stuff. For this kind of operation, String.replace() would work better.

Link to comment
Share on other sites

Okay, new thing: I decided to expand the function to check for all instances of numbers or letters. I created a string containing 0-9 and a-z, and ran the same function that Ingolme created, but this time with an extra feature:If i (our counting variable as we cycle through the letters in that string) is between 0 and 9, then we're in the numbers, so the output says "instances of the number" etc. and if i is greater than 9, we're into the letters, so the output says letter. Fairly simple.In between each if condition, is the same if else-if else process from Ingoleme's function. I was going to say it doesn't work, but I got it working (I had typed 'o' instead of '0'... :)). Except..In IE, all it does is count the length of the string and display that number over and over (36 times), saying (for a three character string, for example): "There were 3 instances of the [number/letter] undefined". At least it observes good grammar, changing from were to was if I only input one character.Here it is in its entirety, with excessive notation so I could try to keep track of my braces and my marbles:

<html><head><title>Combined number and letter analyzer</title><script type="text/javascript">function analyzeMe(scr,outputN) {//initialize a variable containing all alphanumeric characters in a stringvar allChars="0123456789abcdefghijklmnopqrstuvwxyz"//initialize some counting variablesvar j,k,n;//initialize an empty string which will contain the outputvar result=""//loop through all the alphanumeric charactersfor (i=0;i<allChars.length;i++) {//reset nn=0;//loop through all the characters in the user inputed stringfor (j=0;j<scr.length;j++) {//check if the character in the user string matches the character being evaluated in the alphanumeric stringif (scr[j]==allChars[i]) n++//n counts the instances of character j in the user string matching the current character being checked}//if we're checking numbers...if (i<=9) {//and n is zero, then there weren't any instances, so no output, for tidiness and relevanceif (n==0) {result+=""}//if n is one, for grammar purposes, we want a singular instance as the outputelse if (n==1) {//add this output text to the result stringresult+="There was "+ n + " instance of the number "+allChars[i]+".<br />"}//in all other instances, n is greater than oneelse {result+="There were "+ n + " instances of the number "+allChars[i]+".<br />"}}//now we're checking the letterselse if(i>9){//again, if n is zero, no outputif (n==0) {result+=""}//if n is one, singular instanceelse if(n==1) {result+="There was "+ n +" instance of the letter "+allChars[i]+".<br />"}//all other instances, n is pluralelse {result+="There were "+n+" instances of the letter "+allChars[i]+".<br />"}}//send the output string to the empty span tags in the body for displayoutputN.innerHTML=result}}</script></head><body>Please enter any string to see how many instances of each letter and number it contains:<br /><input type="text" id="scrInput" value="12ab" /><br /><input type="button" value="Analyze" onclick="analyzeMe(document.getElementById('scrInput').value,document.getElementById('outputN'))" /><br /><p id="outputN"></p></body></html>

Any thoughts? I get no errors from Firefox Error Console or from IE, and it works in Firefox, Chrome and Opera. Any IE specialists?

Link to comment
Share on other sites

A quick test of IE7 suggests IE does not like to index strings. I had reservations about this, but I couldn't remember why I never use this technique. Now I guess I remember.var s="hello";alert (s[1]);// in FF I got "e".// in IE I got undefined.No reason not to go back to charAt() as long as you use it correctly.

Link to comment
Share on other sites

A quick test of IE7 suggests IE does not like to index strings. I had reservations about this, but I couldn't remember why I never use this technique. Now I guess I remember.var s="hello";alert (s[1]);// in FF I got "e".// in IE I got undefined.No reason not to go back to charAt() as long as you use it correctly.
Thanks for running that test.I have polished the script so that it displays the letter info in one div, and the number in another with headings and some rudimentary formatting, and I'll add to it an 'if IE' clause utilizing the charAt solution. Speaking of: when I tried your splicing function yesterday and reported that it worked, it did and it didn't: sometimes it got it right, sometimes it didn't. I can't recall exactly, so I will go and mess with it and see what happens.This is turning out to be quite a good function for learning purposes. Another question only a novice would think to ask: is it possible to use a loop to write a script to an array so that the rest of the function would work in IE? Or is it not that it doesn't see them as arrays, just that it doesn't like indexing?
Link to comment
Share on other sites

when I tried your splicing function yesterday and reported that it worked, it did and it didn't: sometimes it got it right, sometimes it didn't.
I'm curious. Maybe an IE thing? I haven't tested it there. Also, it's not as flexible as it should be. I should make so you can pass an index and a string and it essentially pastes the string at the index and deletes everything else. As it is (like array.splice), the first two arguments are not optional, so leaving one out creates a mess.
Link to comment
Share on other sites

Okay, back again. I have been playing around with the splice thing. Here's what I've got:

<html><head><title>AlphaCount</title><script type="text/javascript">//define the splice method as part of the String object//i refers to the index where insertions are put//r refers to the number of replacements we want to make//s refers to any string we intend to insert//or operator, allowing s to be returned as empty instead of 'undefined'//in line 3, we build the return string://(0,i) represents the original part between the start of the string and the index we are looking at(one char short, since we're using base 0)//to which we attach the new bit, s, which was passed to the function by the function call//this.substr(i+r) finds the rest of the string, taking into consideration the number of replacements made, to allow for longer bits to be insertedString.prototype.splice=function(i,r,s){s=s||""; return this.substr(0,i) + s + this.substr(i+r) }//initialize some variables needed latervar countvar alphaCount="0000000000000000000000000000000000000"function countLetters(str,output) {//initialize the character string and convert the user input string to lowercase, and counting var jvar allChars="0123456789abcdefghijklmnopqrstuvwxyz"str=str.toLowerCase()var j;//loop through all the characters in the allChars stringfor (i=0;i<allChars.length;i++) {//reset count variablecount=0//loop through all characters in the user input stringfor (j=0;j<str.length;j++) {//check if the character in the user string is the same as the char we're evaluating, and if it is,//retrieve the number already stored in the alphaChar string, let count equal that number, and add oneif (str.charAt(j)==allChars.charAt(i)){count=alphaCount.charAt(i)+1//finally, splice that number into the alphaCount variable:alphaCount=alphaCount.splice((j+10),1,count)}}}var a=alphaCount.charAt(10)var b=alphaCount.charAt(11)var c=alphaCount.charAt(12)var d=alphaCount.charAt(13)var e=alphaCount.charAt(14)var f=alphaCount.charAt(15)var g=alphaCount.charAt(16)var h=alphaCount.charAt(17)var i=alphaCount.charAt(18)var j=alphaCount.charAt(19)var k=alphaCount.charAt(20)var l=alphaCount.charAt(21)var m=alphaCount.charAt(22)var n=alphaCount.charAt(23)var o=alphaCount.charAt(24)var p=alphaCount.charAt(25)var q=alphaCount.charAt(26)var r=alphaCount.charAt(27)var s=alphaCount.charAt(28)var t=alphaCount.charAt(29)var u=alphaCount.charAt(30)var v=alphaCount.charAt(31)var w=alphaCount.charAt(32)var x=alphaCount.charAt(33)var y=alphaCount.charAt(34)var z=alphaCount.charAt(35)msg=a+" instances of the letter a, <br />"+b+" instances of the letter b,<br /> "msg+=c+" instances of the letter c, <br />"+d+" instances of the letter d,<br /> "msg+=e+" instances of the letter e, <br />"+f+" instances of the letter f, <br />"msg+=g+" instances of the letter g, <br />"+h+" instances of the letter h, <br />"msg+=i+" instances of the letter i, <br />"+j+" instances of the letter j, <br />"msg+=k+" instances of the letter k, <br />"+l+" instances of the letter l, <br />"msg+=m+" instances of the letter m, <br />"+n+" instances of the letter n, <br />"msg+=o+" instances of the letter o, <br />"+p+" instances of the letter p, <br />"msg+=q+" instances of the letter q, <br />"+r+" instances of the letter r, <br />"msg+=s+" instances of the letter s, <br />"+t+" instances of the letter t, <br />"msg+=u+" instances of the letter u, <br />"+v+" instances of the letter v, <br />"msg+=w+" instances of the letter w, <br />"+x+" instances of the letter x, <br />"msg+=y+" instances of the letter y, <br />"+z+" instances of the letter z."output.innerHTML=msg}</script></head><body><form>Enter any string: <input type="text" value="678ikjnhbgy7u8ik" id="mainstring" size="30" /><br /><input type="button" value="Count the instances of each letter of the alphabet" onclick="countLetters(document.getElementById('mainstring').value,document.getElementById('output'))" /></form><br /><span id="output"></span></body></html>

Now, that's pretty messy, again with the notations, and I will try to figure out a way to get the variable thing working better, but for now, that's how it is. The (j+10) thing that is passed to the splice function is ugly, but I added the numbers 0-9 into the allChars variable, and I haven't yet added another 10 number holding variables to my ugly list.It doesn't work. Once again, I get no errors on FF error console or IE (I find them the most verbal error modules). I'm not sure what's going wrong. It seems fairly straightforward:I cycle through the allChars string, then through the user input, once per character in the allChars string. I compare the two. If they're the same, I fetch the number currently stored in the alphacount string, add one to it and make the count variable hold that number.Then, I send that number to the splice function, as well as a replacement length of 1 (speaking of, if the number of instances gets to 10 I have problems...), and the index i, because that's where I've got to in the allChars string (the allChars and alphacount string have the same length, so I can have one space in the latter for each character). That whole thing should return a new version of the alphaCount string with a number that is in the same place as the letter it's counting in the allChar string. That wasn't English, but you guys can read the code and follow my notations.I am a little lost.justsomeguy:I tried your version, and it seems to work, but it displays hundreds of alerts. So, I tried adding the alert messages to a result variable (result+="the stuff you had the alert saying, with a break at the end of each line", but that doesn't work. I get no errors in the FireFox error console.My brain is fried for today.

Link to comment
Share on other sites

I tried your version, and it seems to work, but it displays hundreds of alerts.
Yeah I figured it would, that was just a demo though. You can build a string and either alert the string or write it to a div or something.
var result = "";for (var x in found_chars){  result += "Character \"" + x + "\" occurred " + found_chars[x] + " times.<br>";}document.getElementById("feedback").innerHTML = result;

Link to comment
Share on other sites

Yeah I figured it would, that was just a demo though. You can build a string and either alert the string or write it to a div or something.
var result = "";for (var x in found_chars){  result += "Character \"" + x + "\" occurred " + found_chars[x] + " times.<br>";}document.getElementById("feedback").innerHTML = result;

Now, why didn't it work when I did something pretty similar? Code demons, they hate me!Thanks for the fix. Now I just gotta try to understand it. It feels like there isn't enough there to do all that. I feel like I'm missing something. I will work it through tomorrow - I find the only way to really learn is to type it out myself, and try to adapt it a little, so I can see what a function really does. Thanks again!
Link to comment
Share on other sites

justsomeguy: Okay, I mostly get it, and it's a really elegant solution, but one thing I don't get: where does this variable 'x' come from, and how does it do what it does, because it just appears out of nowhere. Is it a special character in JS or something?

Link to comment
Share on other sites

It's just the name of a variable. Convention makes "x" a very popular name for iterating through a for-each loop. It could just as easily have been:

for (var anIndividualChar in found_chars)

Link to comment
Share on other sites

It's just the name of a variable. Convention makes "x" a very popular name for iterating through a for-each loop. It could just as easily have been:
for (var anIndividualChar in found_chars)

I see...I didn't know it could be used like that though. I would have thought x needed to have something assigned to it, though, before you could say for (x in found_chars). Is that due to some property of objects that I'm not aware of? How does x come to recieve a value from justsomeguy's function?
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...