Words, Numbers, and Dates
JavaScript made up of Objects.
Properties - parts of the object.
Methods - actions and object perform.
Object - array
Properties - length
Method - push()
Object - document
Method - write
Whenever you create a new variable and store a value into it, you are creating an instance.
Strings
Length
to determine the length of a string:
name.length
var password = 'sesame';
if (password.length <= 6) {
alert('That password is too short.');
} else if (password.length > 15) {
alert('That password is too long.');
}
Chang the Case of a String
name.toUpperCase
name.toLowerCase
The correct answer to a quiz is LeCuyer, but the person types Lecuyer so they get it wrong.
To correct you can covert both the response and the correct answer to uppercase
if (response.toUpperCase() == correctAnswer.toUpperCase()) {
//correct
} else {
//incorrect
}
Covert to lowercase:
var answer= 'LeCuyer';
alert(answer.toLowerCase());
returns : lecuyer
In both cases the original string is not altered, it is still LeCuyer.
Searching a String: indexOf()
To find out which browser the viewer is using:
Navigator is an object of the web browser, userAgent is the property
<script type="text/javascript">
alert(navigator.userAgent);
</script>
indexOf()
if the search string isn't found the method returns: -1
var browser = navigator.userAgent; // this is a string
if (browser.indexOf('MSIE') != -1) {
// this is Internet Explorer
}
if the searched string is found it returns the position number.
(spaces count as a position: poop face has 0-8
var myString = "Poop Face";
var firstPosition = myString.indexOf('Poo'); // returns 0
var lastPosition = myString.lastIndexOf('Face'); // returns 5
------
Slice
myString.slice(7);
This picks the 6th position of the string.
myString.slice(start,end);
The end is actually the last position +1.
so (0,5) selects the first five letters/positions 0-6
you can also use negative numbers
Regular Expressions
var myMatch = /hello/;
this matches the word hello
How to search using the search() Method
var myRegEx = /To be/;
var quote = 'To be or not to be.';
var foundPosition = quote.search(myRegEx); //returns 0, it returns the first position in the match
Showing posts with label Reading Notes. Show all posts
Showing posts with label Reading Notes. Show all posts
Wednesday, April 27, 2011
Wednesday, April 13, 2011
Chapter 3 / Reading Notes
Adding Logic And Control
Conditional Statements
Used for:
Form Validation : make sure they input information correctly, make sure the field is not empty
Drag and Drop: if the user drags and image somewhere, you can make something happen
Evaluating Input: if you have a popup that asks a question you will want to react accordingly
How to Make a Conditional Statement
There are 3 parts:
1. if
2. ( a true or false question)
3. { if true what should happen}
Comparison Operators
== this is for Equality
<=
<
>= greater than equal to
> greater than
!= not equal
example:
This shows that you can have multiple lines inside the curly brackets.
if (answer == 31) {
alert('Correct. Saturn has 31 moons.');
numCorrect = numCorrect + 1;
}
If they get the answer correct 1 is added to their score (numCorrect).
Finish-off the statement with else:
if (answer == 31) {
alert('Correct. Saturn has 31 moons.');
numCorrect = numCorrect + 1;
} else {
alert("Wrong! That's not how many moons Saturn has, you LOOSER.");
}
Logical Operations
&& AND
|| OR (this is the pipes key which is the key above enter, the same key as \ )
! NEGATION
Multiple Conditions
Example from My Lab Work
var input = prompt('How much money do you have to spend on lunch at Disneyland?');
var cash = Number(input);
if (cash == 2 && cash < 3 ) {
document.write("Vending Machine Soda") }
else if (cash >= 3 && cash < 5 ) {
document.write("You can get a Churro") }
else if (cash >=5 && cash < 10) {
document.write("Kids Hamburger from Tomorrowland Terrace") }
else if (cash >=10 && cash < 20) {
document.write("Chicken Basket from Frontierland")}
else if (cash >=20) {
document.write("Goofy's Kitchen")}
else if (cash <2) {
document.write ("Get more money")}
else {
document.write ('<p>You entered ' + input + ' You did not enter the dollar amount correctly.</p><p>For example: If you have $5.22, please simply enter 5.22')}
var cats == prompt('How many cats do you own?');
if (cats <=3 && cats >=1) {
alert('You are good person');}
else (cats >=4) {
alert('You have too many cats, your house must smell');}
}
Conditionals Tutorial
parseInt( variable,10)
This command takes a value and tries to convert it to an integer.
It is different from Number(), because it will convert a string with numbers as well.
20 years >> 20
If it cannot it returns NaN.
var age = '08 years';
age = parseInt(age,10);
(you have to add the 10 so that it gives you 8, instead of 0. Octal vs Decimal Numbers.)
var luckyNumber = prompt('What is your lucky number?', '');
luckyNumber = parseInt(luckyNumber, 10);
if (isNaN(luckyNumber)) {
luckyNumber = prompt('Please, tell me your lucky number.', '');
}
LOOPS
While Loops
While the condition is true it repeats the chunk of code.
while (condition) {
// javascript to repeat
}
This code writes out the numbers 1-5:
var num = 1;
while (num <= 5) {
document.write('Number ' + num + '<br>');
num = num + 1; }
LOOP and ARRAYS
var animals = ['dogs', 'cats', 'chupacabras', 'bees', 'narnicorns'};
var counter = 0; //sets up a variable counter that will store index number
while (counter < animals.length) { // whileloop. when the index number is less than the total number of items in the array. (animals.length give the total number of items in the array, in this case 5)
document.write(animals[counter] + ', '); //writes that animal
counter++; //adds 1 to the counter
}
For Loops
An easy way to repeat a series of steps
This is a way to re-write the whileLoops example (writing the numbers 1-100), using a forLoop.
for (var num=1; num<=100; num++) { //counter variable; test the condition; add 1 to the number
document.write('Number ' + num + '<br>');
}
Conditional Statements
Used for:
Form Validation : make sure they input information correctly, make sure the field is not empty
Drag and Drop: if the user drags and image somewhere, you can make something happen
Evaluating Input: if you have a popup that asks a question you will want to react accordingly
How to Make a Conditional Statement
There are 3 parts:
1. if
2. ( a true or false question)
3. { if true what should happen}
Comparison Operators
== this is for Equality
<=
<
>= greater than equal to
> greater than
!= not equal
example:
This shows that you can have multiple lines inside the curly brackets.
How many moons does Saturn have?
if (answer == 31) {
alert('Correct. Saturn has 31 moons.');
numCorrect = numCorrect + 1;
}
If they get the answer correct 1 is added to their score (numCorrect).
Finish-off the statement with else:
if (answer == 31) {
alert('Correct. Saturn has 31 moons.');
numCorrect = numCorrect + 1;
} else {
alert("Wrong! That's not how many moons Saturn has, you LOOSER.");
}
Logical Operations
&& AND
|| OR (this is the pipes key which is the key above enter, the same key as \ )
! NEGATION
Multiple Conditions
Example from My Lab Work
var input = prompt('How much money do you have to spend on lunch at Disneyland?');
var cash = Number(input);
if (cash == 2 && cash < 3 ) {
document.write("Vending Machine Soda") }
else if (cash >= 3 && cash < 5 ) {
document.write("You can get a Churro") }
else if (cash >=5 && cash < 10) {
document.write("Kids Hamburger from Tomorrowland Terrace") }
else if (cash >=10 && cash < 20) {
document.write("Chicken Basket from Frontierland")}
else if (cash >=20) {
document.write("Goofy's Kitchen")}
else if (cash <2) {
document.write ("Get more money")}
else {
document.write ('<p>You entered ' + input + ' You did not enter the dollar amount correctly.</p><p>For example: If you have $5.22, please simply enter 5.22')}
Negating a Condition
! NOT
This is like Bizarro Superman, it completely reverses the results of a condition.
if (! valid) {
//print errors and don't submit form
}
! valid can be translated as “if not valid”
if valid is false, then the condition is true
Nesting Conditional Statements
if (pets == 'youHaveCats') { var cats == prompt('How many cats do you own?');
if (cats <=3 && cats >=1) {
alert('You are good person');}
else (cats >=4) {
alert('You have too many cats, your house must smell');}
}
Conditionals Tutorial
parseInt( variable,10)
This command takes a value and tries to convert it to an integer.
It is different from Number(), because it will convert a string with numbers as well.
20 years >> 20
If it cannot it returns NaN.
var age = '08 years';
age = parseInt(age,10);
(you have to add the 10 so that it gives you 8, instead of 0. Octal vs Decimal Numbers.)
var luckyNumber = prompt('What is your lucky number?', '');
luckyNumber = parseInt(luckyNumber, 10);
if (isNaN(luckyNumber)) {
luckyNumber = prompt('Please, tell me your lucky number.', '');
}
LOOPS
While Loops
While the condition is true it repeats the chunk of code.
while (condition) {
// javascript to repeat
}
This code writes out the numbers 1-5:
var num = 1;
while (num <= 5) {
document.write('Number ' + num + '<br>');
num = num + 1; }
LOOP and ARRAYS
var animals = ['dogs', 'cats', 'chupacabras', 'bees', 'narnicorns'};
var counter = 0; //sets up a variable counter that will store index number
while (counter < animals.length) { // whileloop. when the index number is less than the total number of items in the array. (animals.length give the total number of items in the array, in this case 5)
document.write(animals[counter] + ', '); //writes that animal
counter++; //adds 1 to the counter
}
For Loops
An easy way to repeat a series of steps
This is a way to re-write the whileLoops example (writing the numbers 1-100), using a forLoop.
for (var num=1; num<=100; num++) { //counter variable; test the condition; add 1 to the number
document.write('Number ' + num + '<br>');
}
num<= 100; this part is applied at the beginning of the statement and before each time through the loop
Labels:
Reading Notes,
Week 2
Thursday, April 7, 2011
Chapter 2 Notes
Commands
You can recognize commands because they have parenthesis
Web Specific
alert()
document.write()
Universal to Javascript
isNaN() - checks to see if a particular value is a number or not
Types of Data
Numbers
document.write(5 + 15);
whole numbers, decimals, negative
String
can be in double or single quotes
"This isn’t fair" (us double quotes to enclose a string with a single quote inside it)
'He said, "Hello."' is a valid string (how to include quotes in a string)
"He said, "Hello.\ "" (use the \ - an escape character - to tell it to include that quote in the string)
'He said, "This isn\'t fair."' (you have to use the escape character to make that phrase work)
Boolean
you can use boolean value to check if a user did something or not, such as did they supply an email address - true or false
Variables
Stores information for later use
Contain alphanumeric characters and $ and _ (No spaces)
Case-sensitive
Don't use special keywords like alert, break, catch, for, new, this, void.
You can create multiple variables at once like this:
var playerScore, gameRound, playerName;
And you can declare and store multiple pieces of information inside like this:
var playerScore=52, gameRound=1, playerName='Bob';
Basic Math
+ - / *
var price= 5, itemsOrdered=2, totalCost=price*itemsOrdered;
make sure to use parenthesis when having multiple mathematical operations, for example:
(4 + 5) * 10 (this returns 90)
4 + 5 * 10 (this returns 54)
what ever in in the parenthesis happens first.
Combining Strings
Combining strings is called concatenation
var firstName = 'Bob';
var lastName = 'McPoopface';
var fullName = firstName + lastName;
This gives you BobMcPoopface
var firstName = 'Bob';
var lastName = 'McPoopface';
var fullName = firstName + ' ' + lastName;
This gives you Bob McPoopface (with a space)
Combing Numbers and Strings
Automatic Type Conversion
Whenever you use the + operator with a string value and a number it concatenates it to a string
var numOfPoops = 900;
var message='Your dog ate ' + 'numOfPoops' + 'poops today.';
returns: Your dog ate 900 poops today.
Sometimes converting is bad.
For example:
var numOfCatPoops = 25;
var numOfDogPoops = 5;
var numOfPoops = numOfCatPoops + numOfDogPoops;
var message='Your dog ate ' + 'numOfPoops' + 'poops today.';
returns: Your dog ate 255 poops today. (instead of 30)
To prevent this:
(Two ways to convert)
1. Add + to the beginning of the string with the number:
var numTotal = +numStuff
2. Number(variable)
var numTotal = Number(numStuff) + numMoreStuff
You can recognize commands because they have parenthesis
Web Specific
alert()
document.write()
Universal to Javascript
isNaN() - checks to see if a particular value is a number or not
Types of Data
Numbers
document.write(5 + 15);
whole numbers, decimals, negative
String
can be in double or single quotes
"This isn’t fair" (us double quotes to enclose a string with a single quote inside it)
'He said, "Hello."' is a valid string (how to include quotes in a string)
"He said, "Hello.\ "" (use the \ - an escape character - to tell it to include that quote in the string)
'He said, "This isn\'t fair."' (you have to use the escape character to make that phrase work)
Boolean
you can use boolean value to check if a user did something or not, such as did they supply an email address - true or false
Variables
Stores information for later use
Naming Convention for Variables
Starts with a letter, $, _Contain alphanumeric characters and $ and _ (No spaces)
Case-sensitive
Don't use special keywords like alert, break, catch, for, new, this, void.
You can create multiple variables at once like this:
var playerScore, gameRound, playerName;
And you can declare and store multiple pieces of information inside like this:
var playerScore=52, gameRound=1, playerName='Bob';
Basic Math
+ - / *
var price= 5, itemsOrdered=2, totalCost=price*itemsOrdered;
make sure to use parenthesis when having multiple mathematical operations, for example:
(4 + 5) * 10 (this returns 90)
4 + 5 * 10 (this returns 54)
what ever in in the parenthesis happens first.
Combining Strings
Combining strings is called concatenation
var firstName = 'Bob';
var lastName = 'McPoopface';
var fullName = firstName + lastName;
This gives you BobMcPoopface
var firstName = 'Bob';
var lastName = 'McPoopface';
var fullName = firstName + ' ' + lastName;
This gives you Bob McPoopface (with a space)
Combing Numbers and Strings
Automatic Type Conversion
Whenever you use the + operator with a string value and a number it concatenates it to a string
var numOfPoops = 900;
var message='Your dog ate ' + 'numOfPoops' + 'poops today.';
returns: Your dog ate 900 poops today.
Sometimes converting is bad.
For example:
var numOfCatPoops = 25;
var numOfDogPoops = 5;
var numOfPoops = numOfCatPoops + numOfDogPoops;
var message='Your dog ate ' + 'numOfPoops' + 'poops today.';
returns: Your dog ate 255 poops today. (instead of 30)
To prevent this:
(Two ways to convert)
1. Add + to the beginning of the string with the number:
var numTotal = +numStuff
2. Number(variable)
var numTotal = Number(numStuff) + numMoreStuff
Changing the Values in Variables
var score = 0;
score = 100;
var score = 0;
score = score + 100;
Add 100 to what ever value is currently store in "score".
You are preforming a mathematical operation on the value of a variable and then storing that value back into the variable.
Shortcuts:
score += 10;
score = score + 10;
score -= 10;
score = score - 10;
+= -= *= /=
You can also use += for strings:
Adds or subtracts 1
score++
score--
++ --
Arrays
You can store more than one value in a single place, so you don't have to keep creating tons of variables.
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
var listOfStuff = [];
an empty array that can be supplied with information later ( [] two brackets)
Inside of an Array you can store:
Numbers
Strings
Boolean
Arrays
Other Objects
(you can store any combination of from this list)
Getting Items Out of the Array
same as ActionScript, the items have position numbers/index numbers
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July'];
alert(months[2]);
this would return Mar
Change the Value of an Item
months[0] = 'January';
now Jan is changed to January
Get the Last Position of the Array
months[months.length-1];
gets the total number of positions and subtracts 1
so, for months this would be 6 (since I have only listed 7 months)
When working with loops you might want:
var i = 0;
alert(months[i]);
Adding Items to the End of an Array
var properties = ['red', '14px', 'Arial'];
Three ways:
properties[3] = 'bold';
properties[properties.length] = 'bold';
properties.push('bold');
Adding Items to the Beginning of an Array
var properties = ['red', '14px', 'Arial'];
properties.unshift('bold');
you can push and unshift multiple values like this:
properties.push('bold', 'italic', 'underlined');
properties.unshift('bold', 'italic', 'underlined');
push() and unshift() are methods
they return a value, the total items in the array
for example:
var p = [0,1,2,3];
var totalItems = p.push(4,5);
totalItems is 6
Deleting Items from an Array
Similar to Action Script
pop();
shift();
var cats = [Mr.Whiskers, Ugly Cat, Snowball];
var catDeath = cats.pop();
the value catDeath is Snowball
and cats now has [Mr.Whiskers, Ugly Cat]
Adding and Deleting with splice()
this adds and deletes item from the interior positions of the array
var cats = [Mr.Whiskers, Ugly Cat, Snowball, Prof.Muffintop];
cats.splice (1,2);
The 1 is the index number
The 2 is the number of positions to delete
var cats = [Mr.Whiskers,Ugly Cat, Snowball];
Only Mr.Whiskers and Prof.Muffintop remains!
var catsAlive = cats.splice (1,0, 'Snowball Jr., Son of Ugly Cat', "Lil' Kitty Winkins");
var cats = [Mr.Whiskers, Snowball Jr., Son of Ugly Cat, Lil' Kitty Winkins, Prof. Muffintop];
0 indicate you are deleting 0 items
3 new cats are born, now catsAlive has 5 cats!
The Circle of Life, it moves us all.
Replacing Items with splice();
add and delete at the same time
var cats = [Mr.Whiskers, Ugly Cat, Snowball, Prof.Muffintop];
var catsAlive = cats.splice (1,2, 'Snowball Jr., Son of Ugly Cat', "Lil' Kitty Winkins");
var cats = [Mr.Whiskers, Snowball Jr., Son of Ugly Cat, Lil' Kitty Winkins, Prof. Muffintop];
---------------------------------------------------------------------------------------------------------------------------
TUTORIALS
document.write(' <p>');
you can write html into the page
prompt('Tell me your name or I'll doing a flying kick to your face');
this produces a dialogue box similar to alert, but you retrieve an answer
Add 100 to what ever value is currently store in "score".
You are preforming a mathematical operation on the value of a variable and then storing that value back into the variable.
Shortcuts:
score += 10;
score = score + 10;
score -= 10;
score = score - 10;
+= -= *= /=
You can also use += for strings:
var name = 'Bilbo';
var message = 'Hello';
message = message + ' ' + name; >>becomes>> message += ' ' + name;
Adds or subtracts 1
score++
score--
++ --
Arrays
You can store more than one value in a single place, so you don't have to keep creating tons of variables.
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
var listOfStuff = [];
an empty array that can be supplied with information later ( [] two brackets)
Inside of an Array you can store:
Numbers
Strings
Boolean
Arrays
Other Objects
(you can store any combination of from this list)
Getting Items Out of the Array
same as ActionScript, the items have position numbers/index numbers
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July'];
alert(months[2]);
this would return Mar
Change the Value of an Item
months[0] = 'January';
now Jan is changed to January
Get the Last Position of the Array
months[months.length-1];
gets the total number of positions and subtracts 1
so, for months this would be 6 (since I have only listed 7 months)
When working with loops you might want:
var i = 0;
alert(months[i]);
Adding Items to the End of an Array
var properties = ['red', '14px', 'Arial'];
Three ways:
properties[3] = 'bold';
properties[properties.length] = 'bold';
properties.push('bold');
Adding Items to the Beginning of an Array
var properties = ['red', '14px', 'Arial'];
properties.unshift('bold');
properties.push('bold', 'italic', 'underlined');
properties.unshift('bold', 'italic', 'underlined');
push() and unshift() are methods
they return a value, the total items in the array
for example:
var p = [0,1,2,3];
var totalItems = p.push(4,5);
totalItems is 6
Creating a Queue / FIFO
playlist.push('Dumb Song');
nowPlaying = playlist.shift();
This cycles through, you add a song to the end of the list.
Then you play the first song on the list, by removing it and storing it inside nowPlaying. Deleting Items from an Array
Similar to Action Script
pop();
shift();
var cats = [Mr.Whiskers, Ugly Cat, Snowball];
var catDeath = cats.pop();
the value catDeath is Snowball
and cats now has [Mr.Whiskers, Ugly Cat]
Adding and Deleting with splice()
this adds and deletes item from the interior positions of the array
var cats = [Mr.Whiskers, Ugly Cat, Snowball, Prof.Muffintop];
cats.splice (1,2);
The 1 is the index number
The 2 is the number of positions to delete
var cats = [Mr.Whiskers,
Only Mr.Whiskers and Prof.Muffintop remains!
var catsAlive = cats.splice (1,0, 'Snowball Jr., Son of Ugly Cat', "Lil' Kitty Winkins");
var cats = [Mr.Whiskers, Snowball Jr., Son of Ugly Cat, Lil' Kitty Winkins, Prof. Muffintop];
0 indicate you are deleting 0 items
3 new cats are born, now catsAlive has 5 cats!
The Circle of Life, it moves us all.
Replacing Items with splice();
add and delete at the same time
var cats = [Mr.Whiskers, Ugly Cat, Snowball, Prof.Muffintop];
var catsAlive = cats.splice (1,2, 'Snowball Jr., Son of Ugly Cat', "Lil' Kitty Winkins");
var cats = [Mr.Whiskers, Snowball Jr., Son of Ugly Cat, Lil' Kitty Winkins, Prof. Muffintop];
---------------------------------------------------------------------------------------------------------------------------
TUTORIALS
document.write(' <p>');
you can write html into the page
prompt('Tell me your name or I'll doing a flying kick to your face');
this produces a dialogue box similar to alert, but you retrieve an answer
Labels:
Reading Notes,
Week 1
Subscribe to:
Posts (Atom)