JavsScript前端入门

2015-08-12  本文已影响451人  洗阳光

介绍

JavaScript是一种在浏览器中运行的语言,主要用于实现浏览器段的动作,如用户交互,数据处理。在HTML中实现JS有两种办法,一种是通过script标签,另外一种是事件响应代码。
script标签的方式:

  <script>
 document.write("hello,world") //向世界宣布我要学习这门语言啦!
  </script>

事件响应代码:

<html>
 <body onLoad="alert('hi')">//注意单引号和双引号!
</body>
</html>

变量

计算操作符

判断

var age = 20;
 if(age > 18) {
 alert(""成年啦!);
 }
  alert("好啦好啦,知道啦");
 document.write("你的年龄是" + age);
switch {  case;:
case; :
 case: break;
 default: break;}

循环

//求最大公约数
 var u = 42;
 var v = 21;
 var temp= v;
 while(v != 0)
 { teml = u % v;
 u = v;
 v = temp; 
 }
 alert("最大公约数是"+u);
// reverse number
 var number = 23871 ;
 var reverse = 0;
 do
 {
 var lastDigit = number % 10; //取最右边一位
 reverse = (reverse * 10) + lastDigit;
 number = Math.floor(number / 10); //如果没有取整的话会导致浮点数运算错误
 }while(number > 0)
 alert("That number reversed is" + reverse);
//找零钱
 var amt = 74; 
 for (var one = 0; one < amt; one++) 
  for (var five = 0; five < amt/5; five++) 
  for (var ten = 0; ten < amt/10; ten++) 
  for (var twenty = 0; twenty < amt/20; twenty++) 
  if (one+five*5+ten*10+twenty*20 == amt) document.write(one+"张1元"+five+"张5元"+ten+"张10元"+twenty+"张20元等于"+amt+" ");

函数

//求最大公约数
 function gcd ( u , v ) {
 var a = u;
 var b = v;
 var temp = v;
 while (v != 0){
 temp = u%v;
 u = v;
 v = temp;
 }
 document.write (a+"和"+b"的最大公约数是"+n"</br>");
 }
 gcd(42,24)
// 有返回值的函数
 function max (a,b) {a>b?a:b}

数组

var a = new Array ();
var b = new Arrat(size); 
var c = new Arrat (d1,d2,...,dn);
var d = [d1,d2,...,dn];
var colors = new Array ();
 var count = colors.push("red" , "green");
 alert(count);
 count = colors.push "black");
 alert(count);
 var item = colors.pop();
 alert(item);
 alert(colors.length);
...
 var item = = colors.shift();
 alert(item);
 alert(colors.length);

对象

 var o = new Object();
 var circle = {x;,y:,radius:2);
 var book = new Object();
 book.title = "HTML5秘籍";
 book.translator = "李松峰";
 book.chapter1 = new Object();
 book.chapter1.title = "HTML5简介"; //动态添加属性
 delete book.chapter1; //删除对象属性
 book.chapter1 = null;
function Rect (w.h){
 this.width = w;
 this.height = h;
 this.area = function(){
 return this.width*this.height;
 }
 }
 var r = new Rect(5,10);
 alert (r,area());
上一篇下一篇

猜你喜欢

热点阅读