可用 let 一次 binding 多個值
let one = 1, two = 2;
let 宣告變數
const 宣告常數(constant value)
Expression 為產生 value 的片段(produce a value)
'sandwitch';
123;
!false;
另外 ternary operator 也是 expression,因為其目的為評估值(evaluate value)
age>20 ? "You can vote" : "You can not vote"
Statement 執行動作(performs an action)
常見的情況像宣告變數, if/else, switch 跟 loop 都屬於 statement, 因為它們主要目的為控制程式流
let lunch = 'sandwich';
if(age > 20){
return "You can vote";
}else{
return "You can not vote";
}
type | Expression | Statement |
---|---|---|
主要目的 | 產生值 | 執行動作 |
例子 | "string" 7+13 isWeekend ? "go vacation": "need to work" |
declaration, assignment, control flow structure(loop & conditionals) |
do {
statement
}while(condition);
let name = "";
do{
name = prompt("What's your name?");
}while(!name);
要記得在每次loop更新條件的值,否則會 infinite loop
while (condition)
statement
舉例來說像是
let buy_list = ["egg" , "milk" , "teabag"];
while(buy_list.length > 0){
console.log(buy_list.shift());
}
/*
egg
milk
teabag
*/
一般的 for loop 通常長這樣
for (let num=0;num< value;num++){
...
}
let worker = {name: "David" , age: 32, gender:"M"};
for(let prop in worker){
if(worker.hasOwnProperty.call( worker,prop )){
console.log(`${prop}: ${worker[propName]}`)
}
}
/*
name: David
age: 32
gender: M
*/
type | example | common use case in Js |
---|---|---|
camel-case | calculateTotal | variables, functions, properties |
snake-case | calculate_total | data from APIs or configuration files |