iT邦幫忙

2025 iThome 鐵人賽

DAY 2
0

綁定 Binding

可用 let 一次 binding 多個值

let one = 1, two = 2;

變數命名 Naming variables

let 宣告變數
const 宣告常數(constant value)

  • 綁定名稱開頭不可以用數字作為開頭
  • 用到保留字(reserved words)的話會出現 SyntaxError

Expression & Statement

Expression

Expression 為產生 value 的片段(produce a value)

'sandwitch';
123;
!false;

另外 ternary operator 也是 expression,因為其目的為評估值(evaluate value)

age>20 ? "You can vote" : "You can not vote"

Statement

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)

迴圈 Loop (do..while / while / for)

  • 用來多次重複某段程式碼
  • 要注意 loop 的結束條件,每次 loop 後要更新條件的值,避免infinite loop

do ... while

  • do 迴圈的程式碼至少會執行一次,while 則如果初始不符合就不會執行
do {
    statement
}while(condition);
let name = "";

do{
    name = prompt("What's your name?");
}while(!name);

while

要記得在每次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

一般的 for loop 通常長這樣

for (let num=0;num< value;num++){
    ...
}
  • for-of 用於可迭代的資料類型(iteratable type),如 array
  • for-in 用於迭代(iteration)物件的property
    另外還有其他迭代物件屬性的方法,後面再提
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
*/

變數命名的習慣 variable naming convention

type example common use case in Js
camel-case calculateTotal variables, functions, properties
snake-case calculate_total data from APIs or configuration files

上一篇
Chapter 1 資料值、資料型態與運算子-day1
下一篇
Chapter 2 練習題-day3
系列文
溫故而知新:Eloquent Javascript 閱讀筆記4
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言