实现说明
迭代发生在 for (const u of users) 内部——循环之外的语句只执行一遍。
演示用的数据放在这几个模块级绑定中:field、record、users、byId。
使用要点
- 演示输出是带标签的(
keys:、byId.u2:、bracket read:),每个操作都会留下自己的一行标注。
常见问题
有需要管理的依赖吗?
没有。无需声明或安装任何依赖。 状态都挂在模块顶层:field、record、users。
核心语句
const record = { [field]: '[email protected]', ['user_' + field]: 'x' };
const odd = { 'order total': 42, 'a-b': 1 };
const secret = Symbol('secret');
代码示例
// 计算属性键:字面量里用方括号把变量变成键名
const field = 'email';
const record = { [field]: '[email protected]', ['user_' + field]: 'x' };
console.log('keys:', Object.keys(record).join(','));
// 动态建索引:一次遍历把数组折叠成按 id 查找的表
const users = [
{ id: 'u1', name: 'Ada' },
{ id: 'u2', name: 'Ben' },
];
const byId = {};
for (const u of users) {
byId[u.id] = u;
}
console.log('byId.u2:', byId.u2.name);
// 键名含空格或符号时,方括号是唯一读写方式
const odd = { 'order total': 42, 'a-b': 1 };
console.log('bracket read:', odd['order total'], odd['a-b']);
// 方法名可以计算,Symbol 键同样支持
const secret = Symbol('secret');
const box = {
['get' + 'Value']() {
return 7;
},
[secret]: 'hidden',
};
console.log('computed method:', box.getValue(), '| symbol:', box[secret]);