用法
数据类型:
示例代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> var s = "Hello!"; var i = 10; var b = true; var arr = [5, 12, 43, 87.2]; //document.write(arr[2]); //var arr1 = new Array("Heoolpw", "time", "span"); //第二种方式生成数组 var arr2 = new Array(); arr2[0] = "happt"; arr2[1] = "Hellow"; arr2[2] = 1; arr2[3] = 1000; //document.write(arr2[2]); var n = null;//空 var und;//未定义 document.write(n);//输出 null </script> </body> </html>
JS中的运算符
条件语句
if else
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> var u = 10; if (u > 10) { document.write("u大于10"); } else if (u < 10) { document.write("u小于于10"); } else { document.write("u等于10"); } </script> </body> </html>
switch
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> var i = "Hellow"; switch (i) { case "Hellow": document.write("Hellow"); break; case "Time": document.write("Time"); break; default: document.write("default"); break; } </script> </body> </html>
for 和for in循环:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> var arr = [1, 2, 3, 4, 5, 6, 7]; for (var i = 0; i < arr.length; i++) { document.write(arr[i]); document.write("<br/>"); } for (var i in arr) { document.write(arr[i] + "、");//注意for in的用法,i只是下标 } </script> </body> </html>
while和do-while循环:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> var i = 0; while (i < 10) { document.write(i + "<br/>"); i++; } var j = 0; do { document.write(j); j++; } while (j<10); </script> </body> </html>
函数:
函数调用
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> function myfunction(a,b) { var sum = a + b; alert(sum); return sum; } //方式一:在script标签内调用 var sum = myfunction(10, 40); </script> <!--方式二:在HTML中调用--> <input type="button" value="按钮" onclick="myfunction(20,50)" /> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> var n = 50;//全局变量,都可以使用 m = 300;//全局变量,都可以使用 function demo() { var i = 100;//局部变量,只能在该代码块内使用 x = 20;//注意 全局变量,该函数调用后,全局都可以使用 } </script> </body> </html>
End