Events
An event is when sth happens
for example
click on sth
move the mouse
press key
ONLOAD EVENT
onload is triggered when the object has loaded
<!doctype html>
<html>
<body onload="alert('Hello!');">
<p>
</p>
</body>
</html>
FUNCTIONS
a function is a group of code
FUNTION RESPONSE
you can get a response from function
A RECURSIVE FUNCTION
a function can call itself
Handling Bugs
chrome的开发者工具:Console
console.log
see in log (chrome开发者工具)
<script>
console.log('"John" is type: '+ typeof "John"+"\n\n"
+ "3.14 is type: " + typeof 3.14 + "\n\n"
+ "false is type: " + typeof false );
</script>
Comparing Things
<
<=
>
>=
==
!=
<script>
var user_name;
user_name = prompt("what's your name");
if(user_name == "dave"){
alert("Great name!");
}
</script>
make decisioins
if
if else
if else if
if else if ... else
used for a series of comparisons:
switch(variable_name){
case "option_1": do_sth_1();
break;
case "option_2": do_sth_2();
break;
...
default:
}
while loops
indexOf
string.indexOf(” text “);
gives you the location of the first ” text ” in the string.
do while loops
Global Variable Local Variable
creating global variables inside functions
if you assign a value to a variable that has not been declared , it will automatically become a gloabl variable.
example here
<script>
function show_money(){
money = 2;
alert("In the function ,the value is:"+money);
}
show_money();
alert("In the main part , the value is: " + money);
both alert money is 2
Logical Operators
Boolean value : true or false
Logical operators work with Boolean values;
JS has these logical operators:
AND-&&
OR-||
NOT-!
ARRAYS
creating an array
var pets = ["Dog", "Cat" , "Rabbit"];
//without any element inside the boxes;
var pets = new Array(10);
JOIN()
Use array.join(separator) to convert array into string:
var pets = ["Dog", "Cat" , "Rabbit"];
alert(pets.join(" and "));
//Dog and Cat and Rabbit
separator is by default “,”
pets.join();
//Dog,Cat,Rabbit
get sth
alert(pets[2]);
changing sth
pets[2] = "bird";
array size
using array.length
adding to the end
array.push()
var pets = ["Dog", "Cat" , "Rabbit"];
pets.push("Hamster");
adding to the front
array.unshift()
var pets = ["Dog", "Cat" , "Rabbit"];
pets.unshift("Hamster");
removing from the back
array.pop()
var pets = ["Dog", "Cat" , "Rabbit"];
var result = pets.pop();
// "Dog" "Cat"
removing from the front
array.shift()
var pets = ["Dog", "Cat" , "Rabbit"];
var result = pets.shift();
// "Cat" "Rabbit"
combining two arrays
array1.concat(array2)
var pets = ["Dog", "Cat" , "Rabbit", "Hamster"];
var primes = [2 , 3, 5, 7, 11];
var result = pets.concat(primes);
// "Dog" "Cat" "Rabbit" "Hamster" 2 3 5 7 11
Generating Random Numbers
Math.random()
var random_number = Math.random();
//[0,1)
setting up the range(multiply)
random_number = Math.random() * max_value;
//[0, max_value)
Math.floor()
throw away the decimal place
2.888 -> 2
random_number = Math.floor(Math.random()*50);
//integer 0 - 49
if you want to 1-50:
在0-49的基础上 + 1