基本使用

腳本宣告

html 內

使用 <script></script> 元素宣告

<script>
    let age = 18;
</script>

獨立檔案

副檔名為 .js

使用 <script src="jsfile"></script> 引入

js/index.js

let age = 18;

index.html

<script src="js/index.js"></script>

終端機輸出

使用 console.log()

js/index.js

let age = 18;

console.log(age);

變數宣告

使用 let 進行宣告

let age = 18;

let age = 18; 宣告一個變數 age 內容為 18

變數名稱只能是英文跟 _ 開頭,不可用數字開頭以及特殊符號

變數型態

雖然 JavaScript 是弱型態語言,但不代表沒有型態

字串

使用 ' 或是 " 將內容包起來代表字串

let firstName = 'David';
let lastName = "Lin";
let fullName = firstName + ' ' + lastName;

使用 + 運算子執行字串串接

數字

整數或是浮點數(小數點)

let n1 = 1;
let n2 = 1.25;
let n3 = n1 + n2;

console.log(n3);

使用運算子來做處理

當數字遇到字串

let n1 = 1;
let s1 = '10';
let ns = n1 + s1;

console.log(ns);

只要運算過程遇到一個字串型態,全部會被轉為字串處理

顯示型態

typeof

let s1 = '10';

console.log(typeof s1);

型態轉換

字串轉為數字

parseInt(string, radix)

radix 進位系統,使用 10 進制轉換就輸入 10

let n1 = 1;
let s1 = '10';
let ns = parseInt(s1, 10) + n1;

console.log(typeof ns);

偷雞法

let n1 = 1;
let s1 = '10';
let ns = +s1 + n1;

console.log(typeof ns);

變數前面加上 + 轉型為數字(不要有空格)

數字轉文字

使用 .toString() 進行轉型

let n1 = 1;

console.log(typeof n1.toString());

布林 boolean

真(true)跟假(false)

let b1 = true;
let b2 = false;
let b3 = 1;
let b4 = 0;
let b5 = 's';
let b6 = '';
let b7 = -1;
let b8 = 2;

陣列 array

使用 [] 宣告

let a1 = []; // 宣告空陣列
let a2 = [1, 2, 3, 4]; // 宣告並給予初始值

console.log(a2[0]);

索引從 0 開始

增加

a2.push('aaa');

轉字串

a2.join(':');

: 分隔符號,可自訂

尋找

let index = a2.indexOf(2);

回傳符合內容的索引值,找不到時回傳 -1

刪除

.splice(index, delete_count)

a2.splice(0, 1);

從索引 0 刪除 1

物件 object

使用 {} 宣告

let student = {
    name: 'David',
    age: 18,
};

console.log(student);

student.name = 'John';
student.age = 20;

console.log(student);

函數

將事情給予名稱包裝

  • 好理解
  • 可重複使用
  • 彈性高 (可傳參數)

宣告

function add(num1, num2) {
    return num1 + num2;
}

function 宣告關鍵字

add 函數名稱

num1 第一個參數

num2 第二個參數

return num1 + num2 回傳數值

呼叫

函數名稱加上 () 進行呼叫

let calc = add(1, 10);

console.log(calc);

函數與變數

函數也是變數的一種

function add(num1, num2) {
    return num1 + num2;
}

console.log(add(1, 10));

add = 100;

console.log(add(1, 10));

add 將被覆寫為 100,呼叫失敗

關於參數

呼叫函數時,傳遞的參數會自動做變數宣告

flowchart LR
    A[add 1, 10]
    B[num1 = 1 num2 = 10]
    C[return num1 + num2]

    A-->| 初始化參數 | B
    B-->| 執行回傳 | C