参数默认值与展开运算符
约 383 字大约 1 分钟
2026-02-26
参数默认值
ES6 允许在函数声明阶段直接写默认值,避免在函数体内做重复的判空逻辑。
function sum(a = 10, b = 20) {
return a + b
}
console.log(sum()) // 30
console.log(sum(1, 2)) // 3默认值的求值时机
默认值在“函数调用时”求值,并且是惰性执行。
let seed = 0
function next(x = seed + 1) {
return x
}
console.log(next()) // 1
seed = 10
console.log(next()) // 11参数作用域与 TDZ 现象
参数默认值有自己的求值空间,x = x 这类写法容易触发 TDZ。
// ReferenceError
function foo(x = x) {
return x
}rest 参数
rest 可以把不定长参数收敛为真数组,替代早期的 arguments + 转数组写法。
function avg(...nums) {
const total = nums.reduce((acc, n) => acc + n, 0)
return nums.length ? total / nums.length : 0
}
console.log(avg(10, 20, 30)) // 20展开运算符 ...
展开运算符可以把“可迭代结构”摊开,常见于函数调用、数组合并、对象浅拷贝。
函数调用
const args = [1, 2, 3]
console.log(Math.max(...args))数组合并
const a = [1, 2]
const b = [3, 4]
const merged = [...a, ...b]
console.log(merged) // [1, 2, 3, 4]对象浅拷贝
const base = { a: 1, b: 2 }
const next = { ...base, b: 3, c: 4 }
console.log(next) // { a: 1, b: 3, c: 4 }演示:默认值 + rest + spread 协同使用
<!doctype html>
<html lang="zh-CN">
<body>
<pre id="out"></pre>
<script>
function buildMessage(prefix = 'sum', ...nums) {
const total = nums.reduce((acc, n) => acc + n, 0)
return `${prefix}: ${total}`
}
const values = [3, 5, 7]
const message = buildMessage('result', ...values)
document.getElementById('out').textContent = message
</script>
</body>
</html>