← 中文资源

简体中文版本

解构赋值的默认值与剩余项

数组与对象解构都能给缺位补默认值、把余项收进 rest:变量交换一行就能完成,函数参数里解构加默认值可以同时兜住实参缺席的情形。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

first: alpha
second: fallback
rest: [ 'gamma', 'delta' ]
host: api.example.com
port: 8080
options: { timeout: 2500, protocol: 'https' }
swapped: 2 1
connect: localhost:443
connect: api.example.com:8443

实现说明

真正干活的是函数 connect,其余都是接线。

使用要点

  • 跑完文件,输出里会留下标记——first:、second:、rest:。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 文件在加载时定义 connect。

主签名形如 function connect({ host: h = 'localhost', port: p = 443 } = {})

核心语句

return h + ':' + p;

代码示例

// 数组解构:缺位补默认值,余项收进 rest 数组
const [first, second = 'fallback', ...rest] = ['alpha', undefined, 'gamma', 'delta'];
console.log('first:', first);
console.log('second:', second);
console.log('rest:', rest);

// 对象解构:默认值同样生效,剩余键收进 rest 对象
const { host, port = 8080, ...options } = { host: 'api.example.com', timeout: 2500, protocol: 'https' };
console.log('host:', host);
console.log('port:', port);
console.log('options:', options);

// 经典用途:交换两个变量
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log('swapped:', a, b);

// 函数参数解构 + 默认值:连实参缺席都能兜住
function connect({ host: h = 'localhost', port: p = 443 } = {}) {
  return h + ':' + p;
}
console.log('connect:', connect());
console.log('connect:', connect({ host: 'api.example.com', port: 8443 }));