2008年9月18日 星期四

Javascript Object 物件練習

Explicit物件-隱性物件 使用時需加上new 指令
  • User-Define-由使用者自訂的空物件

  • Instant物件-物件內已有特定的功能和屬性
Implicit物件-顯性物件 使用不需加上new指令

今天的課程練習
1.顯示結果連結
2.語法如下



<script language="Javascript">

//一.變數資料型態與html標籤表示法---------------------------------------------


document.write("<h3>一.變數資料型態與html標籤表示法</h3>")

var a=10; //指定資料及型態給變數a

var b; //不指定資料及型態給變數b

document.write("a="+a);

document.write("<br>"); //在 Javascript裡頭,視Html標籤為雙引號

document.write("b="+b+"<br>"); //顯示變數b會有undefined的結果


//二.轉換變數資料型態課本P2-19--------------------------------------------


document.write("<h3>二.轉換變數資料型態</h3>");

nowthen=1.2345678987654321+parseFloat("1.1111111");//parseFloat轉換字串=>浮點數

document.write("nowthen="+nowthen+"<br>");


//三.字串物件-課本P2-14---------------------------------------------------


document.write("<h3>三.字串物件</h3>");

var str1=navigator.appVersion;//抓取瀏覽器版本訊息並指定給str1字串

document.write( str1 + "<p>");


var post1=str1.indexOf("Windows",0);//從第0個字串找起,注意O(歐)是大寫,f小寫

document.write("搜尋Windows的起始字串為 : "+ post1 + "<br>");


var str2=str1.length; //抓取字串物件長度

document.write("str1字串的長度 = " + str2 + "<br>");


var str3=str1.match("MSIE"); //傳回找到的字串,沒有的畫會傳回null

document.write("找尋MSIE字串如果沒有找到吻合的版本傳回"+str3+"<br>");


//四.抓取字串物件中的某一段字--------------------------------------------------

document.write("<h3>四.抓取字串物件中的某一段字</h3>");

var str_moon = "中秋節月圓人團園";//指定字串變數

var str_start = str_moon.indexOf("月圓人團園",0);//找出起始字元位置

var str_word = str_moon.substring(str_start,str_start + 5 );

//列出起始字元開始與結束位置並指定給str_word變數

document.write("列出要找的字串集合 = " + str_moon + "<br>");

document.write( "找出吻合字串的初始值 = "+ str_start+ "<br>");

document.write( "藉由字元起始位置與結束位置,列印出所要的字串 ="+ str_word+ "<br>");


//五.數學函式(課本5-39頁)--------------------------------------------------

document.write("<h3>五.數學函式</h3>"); //

var math01 = Math.sin(20); //使用,sin()函式算出三角函式sin20

var math02 = Math.round((Math.random()*10));

/*1.使用Math.random函式取亂數,發現數值為小數如0.9845....

2.將取回的變數乘上10,發現數值變成如9.845...

3.在外為使用.round函式將math02四捨五入,並指定給math02,也就產生了1~10亂數

*/



//分別列印出各個數值的演變

document.write("sin(20)的值 = " + math01 + "<br>");

document.write( "round定義隨機亂數 = "+ math02 + "<br>");

document.write( "這時就可以跟來賓虎濫你的今日幸運數字(從1~10) = "+ math02 + "<br>");

</script>