Jump to content

Gameboyz's Javascript Queries


gameboyz

Recommended Posts

The postincrement (++) operator is a special construct. You can increase a variable by 2 through the use of the addition-assignment operator, e.g.

i+=2;

switch() statements can always be rewritten just using the if ... else construct, but it is often more optimal to use switch().

Link to comment
Share on other sites

I don't know what spelling has to do with it.Try/catch structures are most useful in other languages where you might experience fatal hardware errors, such as file reading and writing. Javascript doesn't really have things like that. Where you see it most is testing for browser differences, like trying to get an AJAX object. But you can always find a way to test something instead of letting an error happen and then responding.

Link to comment
Share on other sites

I don't know what spelling has to do with it.Try/catch structures are most useful in other languages where you might experience fatal hardware errors, such as file reading and writing. Javascript doesn't really have things like that. Where you see it most is testing for browser differences, like trying to get an AJAX object. But you can always find a way to test something instead of letting an error happen and then responding.
I see, but from W3schools's try and cach statement example, it doesn't really specify the error message. However w3school's onerror does specify. So which is better?
Link to comment
Share on other sites

Try ... catch statements do still have some use in catching runtime errors based on user input, for example division by zero errors. However, try ... catch is memory intensive and there is almost always another way to handle errors, so it is better not to use it.The Array.sort() example is interesting, basically the sort() method will take every possible pair of values from your array and compare them with the function passed to it. The return value then specifies the location in the sorted array that value will take.

Link to comment
Share on other sites

KK thanks I understand now.Anyway the toString() method, is there any real use for it? I mean, the following are exactly the same:

<html><body><script type="text/javascript">var arr = new Array(3);arr[0] = "Jani";arr[1] = "Hege";arr[2] = "Stale";document.write(arr);</script></body></html>

<html><body><script type="text/javascript">var arr = new Array(3);arr[0] = "Jani";arr[1] = "Hege";arr[2] = "Stale";document.write(arr.toString());</script></body></html>

Link to comment
Share on other sites

in that case, toString is called by default, since the destination hint is a string.sometimes this is not the case, as in numbers for instance.you can also create you own .toString methods to display custom objects in a formatted or useful manner, instead of "Object object"it is also good for examining the source code of functions. so yes, there are very good uses for toString, and it pays to know how to use them.

Link to comment
Share on other sites

in that case, toString is called by default, since the destination hint is a string.sometimes this is not the case, as in numbers for instance.you can also create you own .toString methods to display custom objects in a formatted or useful manner, instead of "Object object"it is also good for examining the source code of functions. so yes, there are very good uses for toString, and it pays to know how to use them.
Hi I'm a newbie, can you code out a script where the .toString() method is used (usefully) like what you mentioned? I'll study your script, analyze it and (hopefully) learn from there :]
Link to comment
Share on other sites

cheesy but simple example:

function Person(last,first,age){  this.last = last;  this.first = first;  this.age = age;  this.toString = function(){ return this.first+" "+this.last+" is "+this.age +" years old";}}var mike = new Person("jones","mike",22);alert(mike);alert(Person.toString());

Link to comment
Share on other sites

cheesy but simple example:
function Person(last,first,age){  this.last = last;  this.first = first;  this.age = age;  this.toString = function(){ return this.first+" "+this.last+" is "+this.age +" years old";}}var mike = new Person("jones","mike",22);alert(mike);alert(Person.toString());

Uh but without the ".toString()" it works exactly the same.
Link to comment
Share on other sites

Say you wanted to build a string entirely out of numbers, like if you were making a date or clock. You might end up with something like this:a = 5;b = 5;a.toString() + b.toString() returns "55", not 10In a lot of other situations, Javascript kindly casts numbers into strings automatically:5 + "00" returns "500"For this to happen, the situation has to be unambiguous.5 * "MIKE" returns NaN (not a number)

Link to comment
Share on other sites

Uh but without the ".toString()" it works exactly the same.
what works exactly the same?the object example certainly does not.furthermore, consider that while one appears as a string when using alert (Person), what you see it not actually a string.it's a little confusing because alert hints that it expects a string, so javascript automatically applies the function's .toString() method before displaying it.you can discriminate the difference by applying a string method to the result:
function testMe(){ alert('hello world'); }alert(testMe) // shows the codealert(testMe.toString().toUpperCase()) // shows the code in ALL CAPSalert(testMe.toUpperCase()) // errors, functions don't have toUpperCase()

Link to comment
Share on other sites

cheesy but simple example:
function Person(last,first,age){  this.last = last;  this.first = first;  this.age = age;  this.toString = function(){ return this.first+" "+this.last+" is "+this.age +" years old";}}var mike = new Person("jones","mike",22);alert(mike);alert(Person.toString());

Okay I kind of understand now. By the way under the function "Person", what does the "this.last" represents? Is "this.last" a variable? Didn't know variables can have periods in them :).
Link to comment
Share on other sites

The this keyword refers to the current object (functions are classes in JS). The . is the property access operator, and the last is the actual variable.

function Test() {	this.variable = "test";	this.show = function() { alert(this.variable); }}var test = new Test();alert(test.variable);test.variable = "testing";test.show();

Link to comment
Share on other sites

The this keyword refers to the current object (functions are classes in JS). The . is the property access operator, and the last is the actual variable.
function Test() {	this.variable = "test";	this.show = function() { alert(this.variable); }}var test = new Test();alert(test.variable);test.variable = "testing";test.show();

I see, didn't see this at w3schools's js tutorial (or maybe I missed it)? Haha.
Link to comment
Share on other sites

Having some trouble with cookies, ugh. according to w3schools:

function setCookie(c_name,value,expiredays){var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);document.cookie=c_name+ "=" +escape(value)+[b]((expiredays==null) ? "" : ";expires="+exdate.toGMTString()[/b]);}

The text in bold; I don't understand what the "(expiredays==null) ? "" :" stands for. From http://www.quirksmode.org/js/cookies.html, the syntax is fairly straightforward (except that the value isn't escape()-ed):

function createCookie(name,value,days) {	if (days) {		var date = new Date();		date.setTime(date.getTime()+(days*24*60*60*1000));		var expires = "; expires="+date.toGMTString();	}	else var expires = "";	document.cookie = name+"="+value+expires+"; path=/";}

Can anybody explain? :)

Link to comment
Share on other sites

The text in bold; I don't understand what the "(expiredays==null) ? "" :" stands for.
First, you have to remember that in javascript (unlike some languages), even if a function is declared with arguments, you don't have to pass any or all of the arguments for the function to work. So even though your function is declared like this:function setCookie(c_name,value,expiredays)you can call it like thissetCookie("fav_color", "blue")and not pass any value to expiredays. Now, the ternary operator ( ?: ) is basically an if . . . else operator, and in this case basically does what the if/else construction does in the other function. What it's saying is this: if expiredays is null (because the user passed no value for it), add no text ( "" ) to the cookie. If it DOES have a value, add this text: ;expires="+exdate.toGMTString()As for escape() -- it's a safeguard, in case you end up passing non-alpha-numeric characters to your cookie. If you absolutely know in advance that you won't be doing that, you don't have to use escape. But if you use it, when you GET your cookie, you'll want to use unescape().The two functions are actually quite similar.
Link to comment
Share on other sites

First, you have to remember that in javascript (unlike some languages), even if a function is declared with arguments, you don't have to pass any or all of the arguments for the function to work. So even though your function is declared like this:function setCookie(c_name,value,expiredays)you can call it like thissetCookie("fav_color", "blue")and not pass any value to expiredays. Now, the ternary operator ( ?: ) is basically an if . . . else operator, and in this case basically does what the if/else construction does in the other function. What it's saying is this: if expiredays is null (because the user passed no value for it), add no text ( "" ) to the cookie. If it DOES have a value, add this text: ;expires="+exdate.toGMTString()As for escape() -- it's a safeguard, in case you end up passing non-alpha-numeric characters to your cookie. If you absolutely know in advance that you won't be doing that, you don't have to use escape. But if you use it, when you GET your cookie, you'll want to use unescape().The two functions are actually quite similar.
Why will escape() safeguard against passing non-alpha-numeric characters?
Link to comment
Share on other sites

A good example is the & character. We use it to separate cookie values. But, imagine your page asks your user for the name of their business, and they type "Ben & Jerry's" . You want to store the name in a cookie, so when they come back in two weeks, you can have something say, "Welcome back, Ben & Jerry's!" That & is going to mess things up. You'll end up saying "Welcome back, Ben ". So what escape() does is translate that character into something like %26, which is safe text for a cookie . Unescape translates it back.But as I wrote earlier, if you the script writer are in 100% control of the values that get stored as cookies, you can know in advance if escape() is needed or not.

Link to comment
Share on other sites

Guys why won't my cookie script work? :) Note that I've commented (/* */) some code in the process of troubleshooting and I discovered that the fault lies with the getElementById("setcookie").innerHTML .. the button won't show up. I tried pasting the code into the body element and it works fine. The only way I can get it to work is to replace "onclick="setCookie('name',setcookieinput,1)"" with "onclick="setCookie("name",setcookieinput,1)"".Here's the code:

<html><head></head><body><script type="text/javascript">function checkCookie(name) {cname = getCookie(name);if (cname!=null && cname!="") {document.getElementById("vericook").innerHTML="Cookie is present.";}else {/*document.getElementById("setcookie").innerHTML='<input id="setcookieinput"></input>';*/document.getElementById("setcookie").innerHTML='<input type="button" value="I have entered my name" onclick="setCookie('name',setcookieinput,1)"></input>';}}function getCookie(name) {var nameEQ=name+"=";var ca=document.cookie.split(";");for (var i=0;i<ca.length;i++) {var c=ca[i];while(c.charAt(0)==" ") {c=c.substring(1,c.length);}if (c.indexOf(nameEQ)==0) {return c.substring(nameEQ.length,c.length);}}}/*function setCookie(name,value,expire) {value=document.getElementById("setcookieinput").value;if (expire) {var date=new Date();date.setDate(date.getDate()+expire);var expiry="; expires="+date.toGMTString();}else {var expiry="";}document.cookie=name+"="+escape(value)+expiry+"; path=/";}*/</script><p id="vericook"></p><p id="setcookie"></p><input type="button" value="The Magic Button" onclick="checkCookie('name')"></body></html>

Link to comment
Share on other sites

guys im really lost at the http://www.w3schools.com/js/js_form_validation.asp 1) why isn't it possible to use a variable to define the field name? eg:

<html><head><script type="text/javascript">function validate_required(field,alerttxt){with (field){if (value==null||value=="")  {alert(alerttxt);return false;}else {return true}}}function validate_form(thisform){var email2="email";with (thisform){if (validate_required(email2,"Email must be filled out!")==false)  {email.focus();return false;}}}</script></head><body><form action="submitpage.htm"onsubmit="return validate_form(this)"method="post">Email: <input type="text" name="email" size="30"><input type="submit" value="Submit"> </form></body></html>

2) is there a way to code it such that the field name checks every field of a specific id?

Link to comment
Share on other sites

guys im really lost at the http://www.w3schools.com/js/js_form_validation.asp 1) why isn't it possible to use a variable to define the field name? eg:
<html><head><script type="text/javascript">function validate_required(field,alerttxt){with (field){if (value==null||value=="")  {alert(alerttxt);return false;}else {return true}}}function validate_form(thisform){var email2="email";with (thisform){if (validate_required(email2,"Email must be filled out!")==false)  {email.focus();return false;}}}</script></head><body><form action="submitpage.htm"onsubmit="return validate_form(this)"method="post">Email: <input type="text" name="email" size="30"><input type="submit" value="Submit"> </form></body></html>

2) is there a way to code it such that the field name checks every field of a specific id?

guys anybody? :)
Link to comment
Share on other sites

Archived

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

×
×
  • Create New...