DIV CSS 佈局教程網

JavaScript 基本語法速查:從建立腳本到字串操作
編輯:JavaScript基礎知識     

建立腳本區塊

<script language="JavaScript">
JavaScript code goes here
</script>

隱藏腳本內容

用 HTML 註解把內容包起來,可讓不支援腳本的舊瀏覽器跳過:

<script language="JavaScript">
<!--
document.write("Hello");
// -->
</script>

瀏覽器不支援時的提示

<noscript>
Hello to the non-JavaScript browser.
</noscript>

連結外部腳本檔

<script language="JavaScript" src="/youname.js"></script>

註解

// This is a comment
document.write("Hello"); // This is a comment
/*
All of this
is a comment
*/

輸出到瀏覽器

document.write("<strong>輸出內容</strong>");

定義變數

var myVariable = "some value";

字串串接

var myString = "String1" + "String2";

字串搜尋

<script language="JavaScript">
<!--
var myVariable = "Hello there";
var therePlace = myVariable.search("there");
document.write(therePlace);
// -->
</script>

search() 回傳找到的位置索引,找不到則回傳 -1。若只是單純找子字串,indexOf() 效能更好;search() 的價值在於它接受正規表達式。

字串替換

thisVar.replace("Monday", "Friday");

要注意:replace() 不會改動原字串,而是回傳一個替換後的新字串。要保留結果必須指定給變數:

var result = thisVar.replace("Monday", "Friday");

另外,字串形式的第一個參數只會替換第一個符合項。想全部替換,得用正規表達式加上全域旗標:

var result = thisVar.replace(/Monday/g, "Friday");

補充:現代寫法對照

上面這些語法在今日仍完全有效,但有幾處已有更便利的替代:

  • 宣告變數可用 let / const,能獲得區塊層級作用域。
  • 字串串接可用樣板字面值:`${a} 和 ${b}`。
  • 輸出內容應優先用 DOM API(textContent、innerHTML),而非 document.write()——後者在文件載入完成後呼叫會清空整個頁面。

把這份速查當成「讀懂舊程式碼」的工具,同時知道現代寫法長什麼樣,是最實際的學習路徑。

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