程式開發筆記

JavaScript - Array.prototype.map()

將陣列中每個元素依序丟進 callback 執行,回傳一個「全新」的陣列,不會修改原本的陣列。

const nums = [1, 2, 3];

// map 會回傳新陣列,nums 本身不會被改變
const doubled = nums.map((n) => n * 2);

console.log(doubled); // [2, 4, 6]
console.log(nums);    // [1, 2, 3]

JavaScript - async/await 基本用法

async 函式內部可以用 await 等待一個 Promise 完成,寫法上更接近同步程式碼,錯誤處理用 try/catch。

async function getUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error('取得使用者失敗');
    return await res.json();
  } catch (err) {
    console.error(err);
    return null;
  }
}

C - Hello World

最基本的 C 程式結構:include 標頭檔、main 函式、回傳 0 代表程式正常結束。

#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    return 0;
}

C++ - class 與建構子

C++ 用 class 定義物件,建構子(constructor)在建立實例時自動執行,這裡示範一個簡單的 Point 類別。

#include <iostream>

class Point {
public:
    Point(int x, int y) : x_(x), y_(y) {}
    void print() const {
        std::cout << "(" << x_ << ", " << y_ << ")\n";
    }

private:
    int x_;
    int y_;
};

int main() {
    Point p(3, 4);
    p.print();
    return 0;
}

Python - list comprehension

用一行語法從既有的可疊代物件產生新的 list,比寫 for 迴圈再 append 更簡潔。

nums = [1, 2, 3, 4, 5]

# 只取偶數並平方
squares = [n * n for n in nums if n % 2 == 0]

print(squares)  # [4, 16]