<script>
const apiBase = '= $config['apiBase'] ?>'; // PHP 短標籤輸出
const userId = = json_encode($currentUser->id) ?>; // 安全輸出物件/陣列
const isAdmin = = $currentUser->isAdmin ? 'true' : 'false' ?>;
</script>
關鍵:用 json_encode() 輸出非純量值,自動處理引號、逸出、型別。
<?php
header('Content-Type: application/javascript; charset=UTF-8');
// 這裡可讀取 $_GET、$_SESSION、資料庫等
$apiBase = $config['apiBase'];
?>
const API_BASE = = json_encode($apiBase) ?>;
const USER_ID = = json_encode($userId ?? 0) ?>;
<script src="config.js.php"></script>
缺點:無法瀏覽器快取(每次動態產生)、部署較複雜。
現代替代:用 <script id="config" type="application/json">{...}</script> + JS 讀取 JSON.parse(document.getElementById('config').textContent),靜態 .js 可快取。
function createUser(name, role = 'guest', options = {}) {
// options 解構預設
const {active = true, notify = false} = options;
return {name, role, active, notify};
}
console.log(createUser('Alice')); // {name: "Alice", role: "guest", active: true, notify: false}
console.log(createUser('Bob', 'admin')); // {name: "Bob", role: "admin", active: true, notify: false}
console.log(createUser('Carol', 'editor', {notify: true})); // {notify: true}
function createUser(name, role, options) {
name = name || 'anonymous'; // 注意:''、0、false 也會觸發預設值
role = role !== undefined ? role : 'guest'; // 嚴格判斷 undefined
options = options || {};
options.active = options.active !== undefined ? options.active : true;
options.notify = options.notify !== undefined ? options.notify : false;
return {name, role, ...options};
}
// ES5 arguments(類陣列、無陣列方法、箭頭函式無 arguments)
function oldStyle() {
const args = Array.prototype.slice.call(arguments);
return args.map(x => x * 2);
}
// ES6 剩餘參數(真陣列、語意清晰)
function newStyle(...args) {
return args.map(x => x * 2);
}
// 1. 預設值表達式在呼叫時評估(非定義時)
let counter = 0;
function foo(x = counter++) { return x; }
foo(); // 0
foo(); // 1
// 2. 後參數可引用前參數
function bar(a = 1, b = a * 2) { return [a, b]; }
bar(); // [1, 2]
bar(5); // [5, 10]
bar(5, 20); // [5, 20]
// 3. 解構預設值
function baz({x = 1, y = 2} = {}) { return x + y; }
baz(); // 3
baz({}); // 3
baz({x: 10}); // 12
type="application/json" 資料島 + 靜態 .js 快取arguments,改用 ...rest|| 與 ??(空值合併)差異:val ?? default 只在 null/undefined 觸發