You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将变量值作为点表示法中常量名称的一部分使用?

问题

我通过var opt = $("#select option:selected").val();获取下拉框选中的值(比如option1),想把这个值作为对象属性名的一部分,调用price.option1.savings这样的属性值,让opt替代其中的option1,请问有没有可行的方法?

相关代码示例如下:

原JavaScript代码

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").blur(function() {
    var opt = $("#select option:selected").val();
    var result = price.${!opt}.savings;
    $("#result").html(result);
  });
});

原HTML代码

<select id="select" name="select">
  <option selected ></option>
  <option value="option1">R-11 Batt</option>
  <option value="option2">R-13 Batt</option>
  <option value="option3">R-19 Batt</option>
</select>
<div id="results">{results here}</div>
解决方案

JavaScript中访问对象属性时,当属性名是变量,不能使用点表示法,必须用方括号表示法。把price.${!opt}.savings改成price[opt].savings即可实现需求。

另外注意原代码里的一个小问题:HTML中结果容器的id是results,但JS里用的是$("#result"),需要统一成同一个id,否则无法正确渲染结果。

修正后的完整代码

JavaScript代码

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").blur(function() {
    var opt = $("#select option:selected").val();
    // 先判断opt是否有效,避免选中空选项时报错
    if (opt) {
      var result = price[opt].savings;
      $("#results").html(result);
    } else {
      $("#results").html("请选择一个选项");
    }
  });
});

HTML代码

<select id="select" name="select">
  <option selected ></option>
  <option value="option1">R-11 Batt</option>
  <option value="option2">R-13 Batt</option>
  <option value="option3">R-19 Batt</option>
</select>
<div id="results">{results here}</div>

补充说明

  • 方括号表示法支持用变量作为属性名,这是它和点表示法的核心区别
  • 增加了空选项的判断,避免用户未选择选项时触发错误
  • 如果你的预期结果是11(对应rValue字段),只需要把price[opt].savings改成price[opt].rValue即可

内容的提问来源于stack exchange,提问作者user3152018

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 12:55:30