在 javascript 中,无法用点号(`.`)直接结合变量名访问对象属性;必须改用方括号语法 `obj[variable]`,才能将变量值作为动态键名获取嵌套属性(如 `price[opt].savings`)。
当你需要根据用户选择(例如下拉框
✅ 正确做法是使用方括号语法(bracket notation):
它允许你传入一个字符串、变量或表达式作为属性名,从而实现动态访问:
const price = {
option1: { type: 'R-11', rValue: 11, savings: 0.20, pct: 0.12 },
option2: { type: 'R-13', rValue: 13, savings: 0.22, pct: 0.12 },
option3: { type: 'R-19', rValue: 19, savings: 0.24, pct: 0.12 }
};
$(function() {
$("#select").on('change', function() { // 推荐用 'change' 替代 'blur',语义更准确
const opt = $(this).val(); // 获取选中 option 的 value 值(如 "option1")
// ✅ 动态访问:price["option1"].savings → 0.20
const result = price[opt]?.savings ?? 'N/A'; // 使用可选链 + 空值合并,增强健壮性
$("#result").text(result); // 注意:原示例中 ID 是 "result",非 "results"
});
});? 关键要点说明:
? 扩展提示:若需深层动态路径(如 price[opt].details.cost),仍可组合使用:price[opt]?.details?.cost;但复杂路径建议封装为工具函数或使用 Lodash 的 _.get(price, ['option1', 'savings']) 提升可维护
性。