DIV CSS 佈局教程網

常用 JavaScript 語法 106 條速查整理
編輯:JavaScript綜合知識     

以下整理了 JavaScript 中最常用的語法與內建功能,涵蓋輸出、型別轉換、流程控制、函式、視窗操作、字串與數學處理、日期物件等,適合初學者隨手速查。

基礎輸出與型別

  • 1. 輸出語句:document.write("")。
  • 2. 註解://。
  • 3. HTML 文件順序:document → html →(head, body)。
  • 4. 瀏覽器視窗的 DOM 順序:window →(navigator, screen, history, location, document)。
  • 5. 取得表單元素名稱與值:document.getElementById("元素ID").name(或 value)。
  • 7. 值型別:String、Number、Boolean、Null、Object、Function。
  • 8. 字串轉數值:parseInt()、parseFloat()。
  • 9. 數值轉字串:("" + 變數)。
  • 10. 取字串長度:length。
  • 13. 宣告變數:var。

流程控制與函式

  • 12. 比較運算子:==、!=、>、>=、<、<=。
  • 14. 判斷結構:if(condition){}else{}。
  • 15. 迴圈:for([初始];[條件];[更新]){...}。
  • 16. 中止迴圈:break。
  • 17. 定義函式:function functionName([parameter],...){statement[s]}。

視窗與對話框

  • 19. 開啟/關閉視窗:window.open()、window.close();視窗本身:self。
  • 20. 狀態欄:window.status="字串";。
  • 21. 提示訊息:window.alert("字串");。
  • 22. 確認框:window.confirm();。
  • 23. 輸入框:window.prompt();。
  • 24. 指定顯示位置:window.location.href="URL"。
  • 79. 列印:window.print()。

字串與數學處理

  • 36. 大小寫轉換:string.toUpperCase()、string.toLowerCase()。
  • 37. 尋找子字串位置:String1.indexOf("String2")(回傳 -1 代表找不到)。
  • 38. 取指定位置字元:StringA.charAt(9)。
  • 39. 取子字串:stringA.substring(2,6)。
  • 40. 常用數學函式:Math.PI、Math.max()、Math.pow()、Math.round()、Math.floor(Math.random()*(n+1))(隨機數)。
  • 95. 字串連接:string.concat(string2) 或以 += 連接。
  • 97. 最後一次出現位置:string.lastIndexOf(searchString[,startIndex])。
  • 98. 比對是否匹配:string.match(regExpression)。
  • 99. 置換:string.replace(regExpression, replaceString)。
  • 100. 分割為陣列:string.split(分隔符)。
  • 101. 擷取子字串:string.substr(start[,length])。
  • 104/105. 強制轉整數/浮點數:parseInt(string[,radix])、parseFloat(string[,radix])。
  • 106. 測試是否為數值型:isNaN(變數)。

日期物件

  • 41. 定義日期變數:var today = new Date();。
  • 42. 常用日期方法:getTime()、getFullYear()、getMonth()、getDate()、getDay()、getHours()、getMinutes()、getSeconds(),以及對應的 setXxx() 設定方法(注意月份從 0 起算)。

其他常用項目

  • 54. 定義常數:const;定義變數:var。
  • 60. 是否禁止狀態:isDisabled;設定禁止:disabled。
  • 61. 取得長度:length,回傳整數。
  • 63. 使視窗置於最前:window.focus();反之失去焦點:blur()。
  • 88. location 的屬性:protocol、hostname、port、host、pathname、hash、href。
  • 89. 刷新頁面:window.location.reload()。
  • 90. 歷史瀏覽:window.history.back()、forward()、go(n)。
  • 91. 輸出:document.write() 不換行、document.writeln() 換行。

結語

這份清單涵蓋了 JavaScript 日常開發最常碰到的語法,可作為速查手冊。需提醒的是,部分寫法(如 document.all、showModalDialog)屬於舊式 API,在現代開發中應改用標準 DOM 方法與 window.showModalDialog 的替代方案(如 <dialog> 元素),以確保跨瀏覽器相容性。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved