第三十四天:对象扩展 — 简写、遍历与安全访问
蜗牛往上爬 · 前端工业可视化学习笔记 第 34 篇
对象是 JS 的"一等公民",ES6 给它带来了一大波增强:属性简写让代码更短,Object.entries 让遍历更优雅,可选链?.和空值合并??让深层访问不再报错。今天把这些"现代对象写法"一网打尽。
目录
一、属性简写与方法简写
const id = "CNC-001";
const name = "数控机床";
const temp = 65;
// ES5:写两遍
var device = { id: id, name: name, temp: temp };
// ES6:键名 = 变量名时省略
const device6 = {
id, // 等价于 id: id
name,
temp,
showInfo() { // 方法简写(省略 function)
console.log(this.name);
}
};
高频场景——构造数据:
const createDevice = (id, name, temp) => ({ id, name, temp });
二、计算属性名
// ES5:先创建再添加
var key = "temp";
var obj = {};
obj[key] = 65;
// ES6:方括号直接写在字面量里
const obj6 = {
[key]: 65, // temp: 65
[`${key}_max`]: 80 // temp_max: 80(模板字符串拼接)
};
三、Object.keys / values / entries
const device = { id: "CNC-001", name: "数控机床", temp: 65 };
Object.keys(device); // ["id", "name", "temp"]
Object.values(device); // ["CNC-001", "数控机床", 65]
Object.entries(device); // [["id","CNC-001"], ["name","数控机床"], ["temp",65]]
// ⭐ entries + for...of + 解构 = 最优雅遍历
for (const [key, value] of Object.entries(device)) {
console.log(`${key}: ${value}`);
}
// values 求和:各状态设备数量统计
const stats = { "运行中": 12, "待机": 5, "故障": 2 };
const total = Object.values(stats).reduce((s, n) => s + n, 0); // 19
四、Object.assign 合并对象
const defaults = { theme: "dark", interval: 5000 };
const userConfig = { interval: 1000, token: "abc" };
// assign(目标, ...源):后面的覆盖前面的
const config = Object.assign({}, defaults, userConfig);
// { theme: "dark", interval: 1000, token: "abc" }
// 更简洁:对象展开(效果相同)
const config2 = { ...defaults, ...userConfig };
// 典型场景:默认配置 + 用户配置
const createChart = options =>
Object.assign({ width: 400, height: 300 }, options);
console.log(createChart({ width: 600 }));
// { width: 600, height: 300 }
两者都是浅拷贝——嵌套对象仍共享引用。
五、可选链 ?.(超实用)
安全访问深层属性,不再层层 &&:
const response = { data: { device: { name: "CNC-001" } } };
// ES5:层层判断
const name1 = response && response.data
&& response.data.device && response.data.device.name;
// ES6+:可选链
const name2 = response?.data?.device?.name; // "CNC-001"
// 中间断了也不报错
const bad = { data: null };
console.log(bad?.data?.device?.name); // undefined ✅(不报错)
// 可选方法调用
console.log(device.getName?.()); // 方法存在则调用
console.log(device.getTemp?.()); // 方法不存在返回 undefined
工业场景:解析后端 API 响应时的必备防护——接口字段缺失不再导致页面崩溃。
六、空值合并 ??(比 || 更准)
|| 会把 0、""、false 都当作"没有",?? 只认 null 和 undefined:
const temp = 0;
// ❌ || 的坑:0 是有效温度,却被替换
console.log(temp || 25); // 25(错!)
// ✅ ?? 只在 null/undefined 时用默认值
console.log(temp ?? 25); // 0(正确!)
const name = "";
console.log(name || "未知"); // "未知"
console.log(name ?? "未知"); // ""(空字符串也是有效值时用 ??)
黄金组合:api?.data?.temp ?? 0——安全访问 + 兜底。
七、总结
🎯 对象扩展让"配置对象 + API 数据处理"变得优雅安全。明天学两个新数据结构:Set 与 Map。