实现说明
真正干活的是函数 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 }));