JavaScript specials
Code structure
alert('Hello'); alert('World');
alert('Hello')
alert('World')
alert("There will be an error after this message")
[1, 2].forEach(alert)
function f() {
// no semicolon needed after function declaration
}
for(;;) {
// no semicolon needed after the loop
}
Strict mode
'use strict';
...
Variables
let
const primitive 值不會被改變。
var 老式寫法
變數命名
變數名稱只能用字母、數字、$、_
有多個單字通常使用 camelCase 命名
第一個字不能是數字
有分大小寫
可以用其他語言,但不推薦,因為可能有其他國家的人要閱讀。
有幾個名稱 list of reserved words 已經被使用,無法作為變數。
7 種資料類型
number
整數或有小數點的數字。string
字串。boolean
true
/false
。null
–null
空的或不存在。undefined
–undefined
值沒有被指定。object
複雜的資料結構。symbol
特殊標籤的資料類型。
typeof
顯示資料類型,有以下 2 種例外。
typeof null == "object" // error in the language
typeof function(){} == "function" // functions are treated specially
Interaction
prompt(question, [default]) 問問題返回使用者的答案,選擇 ok 或 cancel。
confirm(question) 問問題返回布林值,選擇 ok 或 cancel。
alert(message) 顯示訊息。
Operators
Arithmetical
+ - * / % **
Assignments
a = 2
a += 2
Bitwise
Ternary
cond ? resultA : resultB
Logical operators
&& || !
Comparisons
> < == != ===
Other operators
,
Loops
// 1
while (condition) {
...
}
// 2
do {
...
} while (condition);
// 3
for(let i = 0; i < 10; i++) {
...
}
The “switch” construct
let age = prompt('Your age?', 18);
// use ===
switch (age) {
case 18:
alert("Won't work"); // the result of prompt is a string, not a number
case "18":
alert("This works!");
break;
default:
alert("Any value not equal to one above");
}
Functions
// Function Declaration
function sum(a, b) {
let result = a + b;
return result;
}
// Function Expression
let sum = function(a, b) {
let result = a + b;
return result;
}
// Arrow functions
// expression at the right side
let sum = (a, b) => a + b;
// or multi-line syntax with { ... }, need return here:
let sum = (a, b) => {
// ...
return a + b;
}
// without arguments
let sayHi = () => alert("Hello");
// with a single argument
let double = n => n * 2;
Last updated
Was this helpful?