
JavaScript是網路上最受歡迎的腳本語言,這門語言可用於HTML 和web,更可廣泛用於伺服器、PC、筆記型電腦、平板電腦和智慧型手機等裝置。
JavaScript特點
JavaScript 已經由ECMA(歐洲電腦製造商協會)透過ECMAScript 實現語言的標準化。
| 年份 | 名稱 | 描述 |
|---|---|---|
| 1997 | ECMAScript 1 | 第一個版本 |
| 1998 | ECMAScript 2 | 版本變更 |
| 1999 | ECMAScript 3 | 新增正規表示式新增try/catch |
| ECMAScript 4 | 沒有發布 | |
| 2009 | ECMAScript 5 | 添加"strict mode",嚴格模式添加JSON 支援 |
| 2011 | ECMAScript 5.1 | 版本變更 |
| 2015 | ECMAScript 6 | 添加類別和模組 |
| 2016 | ECMAScript 7 | 增加指數運算符(**) 增加Array.prototype.includes |
HTML 中的腳本必須位於<script> 與</script> 標籤之間。腳本可放置在HTML 頁面的<body> 和<head> 部分。
通常,我們需要在某個事件發生時執行程式碼,例如當使用者點擊按鈕時。如果我們把JavaScript 程式碼放入函數中,就可以在事件發生時呼叫該函數。
實例1:head中的script函數
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>head標籤中script</title>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "這是我的函數";
}
</script>
</head>
<body>
<h1>我的函數</h1>
<p id="demo">一段</p>
<button type="button" onclick="myFunction()">這是函數</button>
</body>
</html>實例2:body中的script函數
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>body中的script</title>
</head>
<body>
<h1>我的函數</h1>
<p id="demo">我的函式</p>
<button type="button" onclick="myFunction()">點擊一下</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "這是我的函數"
}
</script>
</body>
</html> JavaScript也可以放在外部供調用,注意外部拓展名為.js。
實例3:外部呼叫JavaScript
外部呼叫.js
function myFunction() {
document.getElementById('demo').innerHTML = "這是我的函數"
}呼叫外部script
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>呼叫外部script</title>
</head>
<body>
<p id="demo">一段文字</p>
<button type="button" onclick="myFunction()">試試看</button>
<script src="外部腳本.js"></script>
</body>
</html>JavaScript 可以透過不同的方式來輸出資料:
實例1:aler()彈跳窗輸出
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>alert輸出</title>
</head>
<body>
<h1>alert輸出</h1>
<script>
window.alert(5 + 6)
</script>
</body>
</html>實例2:document.write()輸出
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>document.write輸出</title>
</head>
<body>
<h1>document.write輸出</h1>
<script>
document.write(Date());
document.write("Hello,Web!");
</script>
</body>
</html>實例3:寫到HTMl文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>寫到HTMl文件</title>
</head>
<body>
<h1>寫到HTMl文檔</h1>
<script>
function myFunction() {
document.write("函數輸出");
}
</script>
<button onclick="myFunction()">點這裡</button>
</body>
</html>實例4:使用console.log() 寫入到瀏覽器的控制台
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用console.log()寫入到瀏覽器的控制台</title>
</head>
<body>
<h1>console.log()寫入到瀏覽器的控制台</h1>
<script >
a = 5;
b = 6;
c = a + b;
console.log(c)
</script>
</body>
</html>JavaScript 是一個腳本語言,它是一個輕量級,但功能強大的程式語言。
字面量
在程式語言中,一般固定值稱為字面量。
eyeColor
。
16; // 數字var points = x * 10; // 數字計算var lastName = "Johnson"; // 字串var cars = ["Saab", "Volvo", "BMW"]; // 陣列var person = {firstName:"John", lastName:"Doe"}; // 物件字典JavaScript函數
為了能夠重複引用相同的功能,減少程式碼的書寫和維護的方便,JavaScript提供函數功能,由關鍵字function引導:
function myFunc (a, b) {
return a + b; // 傳回a+b結果} JavaScript特點
相對其它語言,JavaScript有下列特點:
| break | export | interface | instanceof |
| super | boolean | enum | int |
| switch | break | export | interface |
| byte | extends | let | this |
| case | false | long throw catch final native throws char finally this case falselong | throw |
| catch | final | native | throws |
| char | finally | new | creient |
| class | fally | throw sat | native |
| char | finally | new | sex |
| f5 | 月 | ||
| function | function | n | . |
| protected | var | ||
| default | if | public | void |
| delete | implements | return | volatile |
| do | import | short | while |
| double | in | static | with |
JavaScript註解(與Java相同)
// 這是程式碼:單句註釋,在編輯器一般是ctrl + L鍵。
/* 這是程式碼*/:多行註釋,在編輯器一般是ctrl + shift + L鍵。
JavaScript語句向瀏覽器發出的指令,告訴瀏覽器該做什麼。下面的JavaScript語句向id="demo"的HTML元素輸出文字"Hello World!" :
document.getElementById("demo").innerHTML = "Hello World!";與Python不同的是,JavaScript程式碼區塊都是在大括號中的,這點像極了Java。
Java標識符
| 語句 | 描述 |
|---|---|
| break | 用來跳出迴圈。 |
| catch | 語句區塊,在try 語句區塊執行出錯時執行catch 語句區塊。 |
| continue | 跳過循環中的一個迭代。 |
| do ... while | 執行一個語句區塊,在條件語句為true 時繼續執行該語句區塊。 |
| for | 在條件語句為true 時,可以將程式碼區塊執行指定的次數。 |
| for ... in | 用於遍歷數組或物件的屬性(對數組或物件的屬性進行循環操作)。 |
| function | 定義一個函數 |
| if ... else | 用於基於不同的條件來執行不同的動作。 |
| return | 退出函數 |
| switch | 用於基於不同的條件來執行不同的動作。 |
| throw | 拋出(生成)錯誤。 |
| try | 實作錯誤處理,與catch 一同使用。 |
| var | 宣告一個變數。 |
| while | 當條件語句為true 時,執行語句區塊。 |
大部分語言能夠自動補全空格,我們建議在運算子兩邊加上空格,這樣清晰美觀,但是要注意在HTML中空格的是要留意用法的,切勿混為一談。在JavaScript中,下面兩句話是一樣的:
var a = 10; var b=10;
與Python相似,JavaScript也是腳本語言,屬於解釋型。
定義對象
任何事物都是對象,具有相同特徵的事物中抽象化的一個特徵實例。如人類中的小明。
在JavaScript中,物件就是是屬性變數的容器,類似Python中的字典,Java中的雜湊映射,其中定義了物件的屬性。
var people = {
firstName: "Mike",
lastName: "Smith",
age: "18",
address: "Beijing",
job: "Student"
};以上就是物件定義,當然你也可以寫一行,我這樣是為了美觀,以後也強烈大家這樣寫。
存取物件屬性
可以說"JavaScript 物件是變數的容器"。但是,我們通常認為"JavaScript 物件是鍵值對的容器"。鍵值對通常寫法為key : value(鍵與值以冒號分割),鍵值對在JavaScript物件通常稱為物件屬性。我們存取屬性也是透過萬能的" . "(大部分語言都是用的這個)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>這是網站</title>
</head>
<body>
<h1>存取類別屬性</h1>
<!--下面語句一定要在script之前-->
<p id="demo"></p>
<script>
var people = {
firstName: "Mike",
lastName: "Smith",
age: "18",
address: "Beijing",
job: "Student"
};
document.getElementById("demo").innerHTML =
people["firstName"] + "." + people.lastName;
</script>
</body>
</html>兩種存取方式,你可以使用物件名稱.property 或物件名稱.["property"] 。
函數是由事件驅動的或當它被呼叫時執行的可重複使用的程式碼區塊。當呼叫函數時,會執行函數內的程式碼。可以在某事件發生時直接呼叫函數(例如使用者點選按鈕時),並且可由JavaScript 在任何位置進行呼叫。
參數與返回值
在呼叫函數時,您可以向其傳遞值,這些值稱為參數,參數個數不限。
function myFunction( var1 , var2 )
{
程式碼
}
參數在呼叫時,應該嚴格按照其順序傳參,如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>這是一個JavaScript網站</title>
</head>
<body>
<h1>函數參數傳遞問題</h1>
<p>點選下面按鈕呼叫</p>
<button onclick="myFunc('Mike','18','Beijing')">點這裡</button>
<script>
function myFunc(name, age, 加) {
alert("My name is " + name + ", age is " + age + " and my home is in " + address);
}
</script>
</body>
</html> JavaScript函數允許有回傳值,回傳關鍵字為return。當函數回傳值後,函數將停止執行,在return後面的語句將不會被執行。
實例:計算兩個數的乘積並傳回結果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript網站</title>
</head>
<body>
<h1>計算兩個數的值回傳</h1>
<p id="demo"></p>
<script>
function myFunc(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunc(3, 4);
</script>
</body>
</html>變數
JavaScript變數分為兩種:
當我們向未宣告的JavaScript變數指派值時,變數會自動作為window的一個屬性。如下列語句:
name = "Mike";
將宣告window的一個屬性name。非嚴格模式下給未宣告變數賦值建立的全域變量,是全域物件的可配置屬性,可以刪除。如:
var var1 = 1; // 不可配置全域屬性var2 = 2; // 沒有使用var 聲明,可配置全域屬性console.log(this.var1); // 1 console.log(window.var1); // 1 delete var1; // false 無法刪除console.log(var1); //1 delete var2; console.log(delete var2); // true console.log(var2); // 已經刪除錯誤變數未定義
描述
HTML事件是發生在HTML元素上的事情。當在HTML 頁面中使用JavaScript時, JavaScript可以觸發這些事件。
HTML事件可以是瀏覽器行為,也可以是使用者行為。以下是HTM 事件的實例:
通常,當事件發生時,你可以做些事情。在事件觸發時JavaScript可以執行一些程式碼。 HTML元素中可以加入事件屬性,使用JavaScript程式碼來新增HTML元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript事件</title>
</head>
<body>
<h1>JavaScript事件處理兩種方式</h1>
<p id="demoOne"></p>
<button onclick="getElementById('demoOne').innerHTML=Date()">點選查看時間1</button>
<p id="demoTwo"></p>
<button onclick="this.innerHTML=Date()">點擊查看時間2</button>
</body>
</html> JavaScript通常是多行程式碼,比較差常見的就是透過事件屬性呼叫。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript事件</title>
</head>
<body>
<h1>JavaScript事件之屬性呼叫</h1>
<p>點選執行<em>myFunc()</em>函數</p>
<button onclick="myFunc()">點這裡</button>
<p id="one"></p>
<script>
function myFunc() {
document.getElementById("one").innerHTML = Date();
}
</script>
</body>
</html>| 事件 | 描述 |
|---|---|
| onchange | HTML 元素改變 |
| onclick | 使用者點擊HTML 元素 |
| onmouseover | 使用者在一個HTML元素上移動滑鼠 |
| onmouseout | 使用者從一個HTML元素上移開滑鼠 |
| onkeydown | 使用者按下鍵盤按鍵 |
| onload | 瀏覽器已完成頁面的載入 |
後續會繼續學習更多事件。
事件作用
事件可以用於處理表單驗證,使用者輸入,使用者行為及瀏覽器動作:
可以使用多種方法來執行JavaScript事件代碼:
字串:一系列字元的集合。
var a = "abc"; var b = "Hello";
與Python類似,可以使用索引來存取字串中的每個字元:
var c = b[1]; // e
length
該屬性可以計算字串的長度。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字串長度</title>
</head>
<body>
<script>
var txtOne = "Hello World!";
document.write("<p>" + txtOne.length + "</p>");
var txtTwo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write("<p>" + txtTwo.length + "</p>");
</script>
</body>
</html> JavaScript也有一些特殊字符,例如當我們要列印引號時,需要加上“”來進行轉義,否則編譯器無法解析。
| 程式碼 | 輸出 |
|---|---|
| ' | 單引號 |
| " | 雙引號 |
| \ | 反斜線 |
| n | 換行 |
| r | 回車 |
| t | tab(製表符) |
| b | 退格符號 |
| f | 換頁符號 |
字串作為物件
通常, JavaScript字串是原始值,可以使用字元建立: var firstName = "Mike",但我們也可以使用new關鍵字將字串定義為一個物件:var firstName = new String("Mike"),這點與Java類似
| 。 | |
| | |
|---|---|
| | |
| | |
| | |
|---|---|
| | |
| | 指定索引位置字元的Unicode 值 |
| concat() | 連接兩個或多個字串,傳回連接後的字串 |
| fromCharCode() | 將Unicode 轉換為字串 |
| indexOf() | 傳回字串中檢索指定字元第一次出現的位置 |
| lastIndexOf() | 傳回字串中檢索指定字元最後一次出現的位置 |
| localeCompare() | 以本地特定的順序來比較兩個字串 |
| match() | 找到一個或多個正規表示式的匹配 |
| replace() | 替換與正規表示式匹配的子字串 |
| search() | 檢索與正規表示式相符的值 |
| slice() | 提取字串的片段,並在新的字串中返回被提取的部分 |
| split() | 把字串分割為子字串數組 |
| substr () | 從起始索引號擷取字串中指定數目的字元 |
| substring() | 擷取字串中兩個指定的索引號之間的字元 |
| toLocaleLowerCase() | 根據主機的語言環境將字串轉換為小寫,只有幾種語言(如土耳其語)具有地方特有的大小寫映射 |
| toLocaleUpperCase() | 根據主機的語言環境把字符串轉換為大寫,只有幾種語言(如土耳其語)具有地方特有的大小寫映射 |
| toLowerCase() | 把字符串轉換為小寫 |
| toString() | 回傳字串物件值 |
| toUpperCase() | 把字串轉換為大寫 |
| trim() | 移除字串首尾空白 |
| valueOf() | 回傳某個字串物件的原始值 |
==與===差異
1、對於string、number 等基礎型,== 和=== 是有差異的
2.對於Array,Object 等高階類型,== 和=== 是沒有區別的
進行"指標位址" 比較
3、基礎類型與進階類型,== 和=== 是有區別的
4、!= 為== 的非運算,!== 為=== 的非運算
var num=1; var str="1"; var test=1; test == num //true 相同型別相同值test === num //true 相同型別相同值test !== num //false test與num型別相同,其值也相同, 非運算肯定是false num == str //true 把str轉換為數字,檢查其是否相等。 num != str //false == 的非運算num === str //false 類型不同,直接回傳false num !== str //true num 與str型別不同表示其兩者不等非運算自然是true啦
| 運算子 | 描述 | 範例 | x 運算結果 | y 運算結果 |
|---|---|---|---|---|
| + | 加法 | x =y+2 | 7 | 5 |
| - | 減法 | x=y-2 | 3 | 5 |
| * | 乘法 | x=y*2 | 10 | 5 |
| / | 除法 | x=y/2 | 2.5 | 5 |
| % | 取模(餘數) | x=y%2 | 1 | 5 |
| ++ | 自增 | x=++y | 6 | 6 |
| x=y++ | 5 | 6 | ||
| -- | 自減 | x=--y | 4 | 4 |
| x=y-- | 5 | 4 |
| 運算子 | 範例 | 等同於 | 運算結果 |
|---|---|---|---|
| = | x=y | x=5 | |
| += | x+=y | x=x+y | x=15 |
| -= | x-=y | x=xy | x=5 |
| *= | x*=y | x=x*y | x=50 |
| /= | x/=y | x= x/y | x=2 |
| %= | x%=y | x=x%y | x=0 |
| 運算子 | 描述 | 比較 | 回傳值 |
|---|---|---|---|
| == | 等於 | x==8 | false |
| x==5 | true | ||
| = == | 絕對等於(值和型別均相等) | x==="5" | false |
| x===5 | true | ||
| != | 不等於 | x!=8 | true |
| !== | 不絕對等於(值和型別有一個不相等,或兩個都不相等) | x!=="5" | true |
| x!==5 | false | ||
| > | 大於 | x>8 | false |
| < | 小於 | x<8 | true |
| >= | 大於或等於 | x>=8 | false |
| <= | 小於或等於 | x<= 8 | true |
| <= | 小於或等於 | x<=8 | true |
| 運算子 | 描述 | 範例 |
|---|---|---|
| && | and | (x < 10 && y > 1) 為true |
| || | 或 | (x== 5 || y==5) 為false |
| ! | not | !(x==y) 為true J |
avaScript 也包含了基於某些條件對變數進行賦值的條件運算子。如:
variablename=(condition)?value1:value2
在JavaScript 中,我們可使用以下條件語句:
if語句
條件為true時才會執行程式碼。如:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>JavaScript網站</title>
</head>
<body>
<h1>這是if語句</h1>
<button onclick="myFunc()">點這裡</button>
<p id="one"></p>
<script>
function myFunc() {
var x = "";
var time = new Date().getHours();
if (time < 20) {
x = "Hello, Before 20:00";
}
document.getElementById("one").innerHTML = x;
}
</script>
</body>
</html> if...else語句
使用if....else語句在條件為true時執行程式碼,在條件為false時執行其他程式碼。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>JavaScript網站</title>
</head>
<body>
<h1>這是if...else語句</h1>
<button onclick="myFunc()">點這裡</button>
<p id="one"></p>
<script>
function myFunc() {
var x = "";
var time = new Date().getHours();
if (time < 20) {
x = "Hello, Before 20:00";
}else {
x = "Hello, After 20:00";
}
document.getElementById("one").innerHTML = x;
}
</script>
</body>
</html>多重if..else語句
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>JavaScript網站</title>
</head>
<body>
<h1>多重if...else語句</h1>
<button onclick="myFunc()">點這裡</button>
<p id="one"></p>
<script>
function myFunc() {
var x = "";
var time = new Date().getHours();
if (time < 12) {
x = "早上好";
} else if (time < 14) {
x = "中午好";
}
else {
x = "下午好";
}
document.getElementById("one").innerHTML = x;
}
</script>
</body>
</html> switch語句
使用switch語句來選擇要執行的多個程式碼區塊之一。如:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>JavaScript網站</title>
</head>
<body>
<h1>switch語句</h1>
<button onclick="myFunc()">點這裡</button>
<p id="one"></p>
<script>
function myFunc() {
var x = "";
var time = new Date().getMonth();
switch (time) {
case 0:
x = "January";
break;
case 1:
x = "February";
break;
case 2:
x = "March";
break;
case 3:
x = "April";
break;
case 4:
x = "May";
break;
case 5:
x = "Jane";
break;
case 6:
x = "July";
break;
case 7:
x = "August";
break;
case 8:
x = "September";
break;
case 9:
x = "October";
break;
case 10:
x = "November";
break;
case 11:
x = "December";
break;
default:
x = "ERROR";
}
document.getElementById("one").innerHTML = x;
}
</script>
</body>
</html>JavaScript 支援不同類型的迴圈:
for迴圈
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript循環</title>
</head>
<body>
<h1>點選按鈕循環程式碼5次。 </h1>
<button onclick="myFunc()">點這裡</button>
<p id="demo"></p>
<script>
function myFunc() {
var x = "";
for (var i = 0; i < 5; i++) {
x = x + "該數字為" + i + "<br>";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html> fo /in循環
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>點選下面的按鈕,遍歷物件person屬性</p>
<button onclick="myFunc()">點這裡</button>
<p id="one"></p>
<script>
function myFunc() {
let x;
let text = "";
const person = {
firstName: "Bill",
lastName: "Gates",
age: 56
};
for (x in person) {
text = text + " " + person[x];
}
document.getElementById("one").innerHTML = text;
}
</script>
</body>
</html> while循環
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>點選按鈕,i小於5就會列印輸出</p>
<button onclick="myFunc()">點這裡</button>
<p id="one">顯示在這裡</p>
<script>
function myFunc() {
let x = "", i = 0;
while (i < 5) {
x = x + "這個數字為" + i + "<br>";
i++;
}
document.getElementById("one").innerHTML = x
}
</script>
</body>
</html> do/while循環
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>點選按鈕,列印小於5的數</p>
<button onclick="myFunc()">點這裡</button>
<p id="one"></p>
<script>
function myFunc() {
let x = "";
let i = 0;
do {
x = x + "該數字為" + i + "<br>";
i++;
}
while (i < 5);
document.getElementById("one").innerHTML=x;
}
</script>
</body>
</html> for迴圈和while迴圈比較
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>這是funcOne</p>
<button onclick="funcOne()">點選funcOne</button>
<p id="one">funcOne在這裡</p>
<p>這是funcTwo</p>
<button onclick="funcTwo()">點選funcTwo</button>
<p id="two">funcTwo在這裡</p>
<script>
function funcOne() {
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let i = 0;
let addRes = 0;
while (numbers[i]) {
addRes += numbers[i];
i++;
}
document.getElementById("one").innerHTML = addRes + "<br>";
}
function funcTwo() {
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let i = 0;
let mulRes = 1;
for (; numbers[i];) {
mulRes *= numbers[i];
i++;
}
document.getElementById("two").innerHTML = mulRes + "<br>";
}
</script>
</body>
</html> Break和Continue
break 語句用來跳出迴圈。 continue 用於跳過循環中的一個迭代。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>這是continue和break語句</p>
<button onclick="funcOne()">點選funcOne</button>
<p id="one">這是funcOne</p>
<br>
<br>
<br>
<br>
<br>
<br>
<button onclick="funcTwo()">點選funcTwo</button>
<p id="two">這是funcTwo</p>
<script>
function funcOne() {
let x = "";
let i = 0;
for (i = 0; i < 10; i++) {
if (i < 5) {
break;
}
x = x + "該數字為" + i + "<br>";
}
document.getElementById("one").innerHTML = x;
}
function funcTwo() {
let x = "";
let i = 0;
for (i = 0; i < 10; i++) {
if (i === 8) {
continue;
}
x = x + "該數字為" + i + "<br>";
}
document.getElementById("two").innerHTML = x;
}
</script>
</body>
</html> 使用typeof操作符來偵測變數的資料類型。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p id="one"></p>
<script>
document.getElementById("one").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1, 2, 3, 4] + "<br>" +
typeof {name: 'john', age: 34};
</script>
</body>
</html>在JavaScript中,陣列是一種特殊的物件類型。 因此typeof [1,2,3,4] 回傳object。
null表示空,也就是」什麼都沒有「。當使用typeof 檢測時,傳回object。物件可以使用undefined來清空。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>one:</p>
<p id="one"></p>
<p>two:</p>
<p id="two"></p>
<script>
var person = {firstName: "Bill", lastName: "Gates", age: 50};
var person = null;
document.getElementById("one").innerHTML = typeof person;
person = undefined
document.getElementById("two").innerHTML = typeof person;
</script>
</body>
</html> constructor屬性傳回所有JavaScript變數的建構子。可以使用constructor屬性來查看物件是否為陣列或是否為日期(包含字串"Date")等。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>constructor屬性傳回變數或建構子</p>
<p id="one">HRER</p>
<script>
document.getElementById("one").innerHTML =
"Hello".constructor + "<br>" +
3.14.constructor + "<br>" +
false.constructor + "<br>" +
[1, 2, 3].constructor + "<br>" +
{name: "Hello", age: 18}.constructor + "<br>" +
new Date().constructor + "<br>" +
function () {
}.constructor;
</script>
</body>
</html>JavaScript 變數可以轉換為新變數或其他資料型別:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>String()方法可以將數字轉換為字串</p>
<p id="one">HERE</p>
<p>toString()方法可以將數字轉換為字串</p>
<p id="two">HERE</p>
<script>
let x = 123;
document.getElementById("one").innerHTML =
String(x) + "<br>" +
String(123) + "<br>" +
String(100 + 23);
document.getElementById("two").innerHTML =
x.toString() + "<br>" +
(123).toString() + "<br>" +
(100 + 123.2).toString();
</script>
</body>
</html>Operator+可用於將變數轉換為數字:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<P>typeof運算子傳回變數或表達式類型</P>
<button onclick="myFuncOne()">CLICK HERE ONE</button>
<p id="one">HERE</p>
<button onclick="myFuncTwo()">CLICK HERE TWO</button>
<p id="two">HERE</p>
<script>
function myFuncOne() {
let y = "5";
let x = +y;
document.getElementById("one").innerHTML =
typeof y + "<br>" + x + "<br>" + typeof x;
}
function myFuncTwo() {
let a = "Hello";
let b = +a;
document.getElementById("two").innerHTML =
typeof a + "<br>" + b + "<br>" + typeof b;
}
</script>
</body>
</html> | 原始值 | 轉換為數字 | 轉換為字串 | 轉換為布林值 |
|---|---|---|---|
| false | 0 | "false" | false |
| true | 1 | "true" | true |
| 0 | 0 | "0" | false |
| 1 | 1 | "1" | true |
| "0" | 0 | "0 " | true |
| "000" | 0 | "000" | true |
| "1" | 1 | "1" | true |
| NaN | NaN | "NaN" | false |
| Infinity | Infinity | "Infinity" | true |
| -Infinity | -Infinity | "-Infinity" true "" 0 "" false "20" 20 "finity "-Infinity" true "" 0 "" false "20" 20 "finity "-Infinity" true "" 0 "" false "20" 20 "finity "-Infinity" | true |
| "" | 0 | "" | false |
| "20" | 20 | "finity" 20" | true |
| "Runoob" | NaN | "Runoob" | true |
| [ ] | 0 | "" | true |
| [20] | 20 | "20" | true |
| [10,20] | NaN | "10,20" | true |
| ["Runoob"] | NaN | "Runoob" | true |
| ["Runoob ","Google"] | NaN | "Runoob,Google" | true |
| function(){} | NaN | "function(){}" | true |
| { } | NaN | "[object Object]" | true |
| null | 0 | "null" | false |
| undefined | NaN | "undefined" | false |
正規表示式(英文:Regular Expression,在程式碼中常簡寫為regex、regexp或RE)使用單一字串來描述、匹配一系列符合某個句法規則的字串搜尋模式。
search()
用於檢索字串中指定的子字串,或檢索與正規表示式相符的子字串,並傳回子字串的起始位置。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>收索字串,匹配位置</p>
<button onclick="myFuncOne()">CLICK HERE ONE</button>
<p id="one">HERE</p>
<button onclick="myFuncTwo()">CLICK HERE TWO</button>
<p id="two">HERE</p>
<script>
function myFuncOne() {
let str = "Hello,World!";
document.getElementById("one").innerHTML = str.search(/World/i);
}
function myFuncTwo() {
let str = "Welcome to China!";
document.getElementById("two").innerHTML = str.search("China");
}
</script>
</body>
</html> replace()
用於在字串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>正規表示式replace()替換</p>
<button onclick="myFuncOne()">CLICK ONE</button>
<p id="one">Hello,Java</p>
<button onclick="myFuncTwo()">CLICK TWO</button>
<p id="two">Hello,Java</p>
<script>
function myFuncOne() {
let str = document.getElementById("one").innerHTML;
document.getElementById("one").innerHTML = str.replace(/Java/i, "Python");
}
function myFuncTwo() {
let str = document.getElementById("two").innerHTML;
document.getElementById("two").innerHTML = str.replace("Java","JavaScipt");
}
</script>
</body>
</html>正規表示式模式
| 修飾符 | 描述 |
|---|---|
| i | 執行對大小寫不敏感的匹配。 |
| g | 執行全域匹配(查找所有匹配而不是在找到第一個匹配後停止)。 |
| m | 執行多行匹配。 |
| 表達式 | 描述 |
|---|---|
| [abc] | 查找方括號之間的任何字元。 |
| [0-9] | 找出任何從0 至9 的數字。 |
| (x|y) | 找出任何以| 分隔的選項。 |
| 量詞 | 描述 |
|---|---|
| n+ | 符合任何包含至少一個n的字串。 |
| n* | 符合任何包含零個或多個n的字串。 |
| n? | 符合任何包含零個或一個n的字串。 |
test()
用於偵測字串是否符合某個模式,如果字串中包含符合的文本,則傳回true,否則傳回false。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<script>
let obj = new RegExp("e");
let boolOne = obj.test("Hello,This is JavaScript");
let boolTwo = obj.test("This is JavaScript");
document.write(boolOne + "<br>" + boolTwo);
</script>
</body>
</html> exec()
用於檢索字串中的正規表示式的匹配,該函數會傳回一個數組,其中存放匹配的結果。如果未找到匹配,則傳回值為null。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<script>
let obj = new RegExp(/e/);
resOne = obj.exec("Hello,This is JavaScript");
resTwo = obj.exec("This is JavaScript");
/*沒有就是null*/
document.write(resOne + "<br>" + resTwo);
</script>
</body>
</html>錯誤類型
try...catch
try語句允許我們定義在執行時進行錯誤測試的程式碼區塊,catch語句允許我們定義當try程式碼區塊發生錯誤時,所執行的程式碼區塊。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<input type="button" value="查看訊息" onclick="myFunc()">
<script>
let txt = "";
function myFunc() {
try {
alert111("Hello,World!")
}
catch (err) {
txt = "這裡有一個錯誤nn";
txt += "錯誤描述:" + err.message + "nn";
txt += "點選確定繼續nn";
alert(txt)
}
}
</script>
</body>
</html> throw
throw語句允許我們建立自訂錯誤。正確的技術術語是:創建或拋出異常(exception)。如果把throw與try和catch一起使用,那麼您能夠控製程式流,並產生自訂的錯誤訊息。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>請輸入一個5-10之間的數字</p>
<label for="one"></label><input id="one" type="text">
<button type="button" onclick="myFunc()">CLICK</button>
<p id="message">HERE</p>
<script>
function myFunc() {
let message;
let x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("one").value;
try {
if (x === "")
throw "值為空";
if (isNaN(x))
throw "不是數字";
x = Number(x);
if (x < 5)
throw "太小";
if (x > 10)
throw "太大";
} catch (error) {
message.innerHTML = "錯誤" + error;
}
}
</script>
</body>
</html>JavaScript 函數有4 種呼叫方式,每種方式的差異在於this的初始化。一般而言,在Javascript中,this指向函數執行時的目前物件。
呼叫1:以函數呼叫
one
function myFunc(a, b) {
return a * b;
}
myFunc(1, 2); two
function myFunc(a, b) {
return a * b;
}
window.myFunc(1, 2);呼叫2:函數作為方法呼叫
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>函數作為方法呼叫</p>
<p id="one">HERE</p>
<script>
let myObject = {
firstName: "Bill",
lastName: "Gates",
fullName: function () {
return this.firstName + " " + this.lastName;
}
};
document.getElementById("one").innerHTML = myObject.fullName();
</script>
</body>
</html>呼叫3:使用建構函式呼叫函數
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>在這個實例中,myFunc()是函數的建構子</p>
<p id="one"></p>
<script>
function myFunc(argOne, argTwo) {
this.Name = argOne;
this.Number = argTwo;
}
let x = new myFunc("Hello", 123);
document.getElementById("one").innerHTML = x.Name;
</script>
</body>
</html>呼叫4:作為函數方法調動函數
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>作為函數方法調動函數</p>
<p id="one">HERE</p>
<script>
let obj, array;
function myFunc(a, b) {
return a * b;
}
array = [5, 6];
obj = myFunc.apply(obj, array);
document.getElementById("one").innerHTML = obj;
</script>
</body>
</html>內嵌函數
實際上,在JavaScript中,所有函數都能存取它們上一層的作用域。 JavaScript支援巢狀函數,巢狀函數可以存取上一層的函數變數。內嵌函數plus()可以存取父函數的counter變數:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>內嵌函數</p>
<p id="one">HERE</p>
<script>
document.getElementById("one").innerHTML = add();
function add() {
let counter = 0;
function plus() {
counter += 1;
}
plus();
return counter;
}
</script>
</body>
</html>閉包
函數的自我呼叫稱為bibao
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>局部計數器</p>
<button type="button" onclick="myFunc()">計數器</button>
<p id="one">HERE</p>
<script>
let add = (function () {
let counter = 0;
return function () {
return counter += 1;
}
})();
function myFunc() {
document.getElementById("one").innerHTML = add();
}
</script>
</body>
</html>