【问题标题】:How to get the value number in the javascript object?如何获取javascript对象中的值编号?
【发布时间】:2019-12-16 15:43:46
【问题描述】:

我正在为货币兑换示例构建一个 Web 表单。这是我最初编写的示例 HTML 和 Javascript。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Currency Exchange</title>
    <link rel="stylesheet" type="text/css" href="styles/styles.css" />
  </head>

  <body>
    <h1>Currency Exchange Rates to US Dollar</h1>
    <select id="currencies" onchange="getCurrency()">
      <option value="">Select a Currency</option>
      <option>UK Pounds</option>
      <option>Euros</option>
      <option>Yen</option>
      <option>Yuan</option>
      <option>Swiss Francs</option>
      <option>Canadian Dollars</option>
    </select>
    <p id="exchangerate"></p>
  </body>
</html>

抱歉这个菜鸟问题。我正在尝试将货币数据存储在 JS 集合中,并希望有一个下拉菜单。我应该如何从对象中获取值以显示在下拉菜单中?

我一直在尝试将数据存储在一个对象中,但它似乎没有按应有的方式工作。还想检查单引号是否对变量正确——这是我发现的唯一方法。

let rates = {
    UKPounds: 0.75,
    Euros: 0.9,
    Yen: 109.44,
    Yuan: 7.02,
    SwissFrancs: 0.98,
    CanadianDollars: 1.32
  };

以下是我获得价值的第一个解决方案。你们认为在这里使用 for 循环是否合适?

let cur_type = document.getElementById('currencies').value; //assign the id 'currencies' to cur_type and get value
  cur_type = cur_type.trim(); // remove all the leading and the trailing spaces in the string.
  if (rates.hasOwnProperty(cur_type)) { // get the property of rates and add to cur_type
    document.getElementById('exchangerate').innerHTML =
      'One US Dollar buys you ' + rates[cur_type] + ' ' + rates; // get id 'exchangerate' and dislay in the browser the value of each property following by the names (rates) of each property.
  }
}

【问题讨论】:

  • 你指的是哪个单引号?
  • rates 对象内的单引号。例如:“UKPounds”:0.75,“Euro”:0.9,等等..
  • 拜托,您能否更好地解释您想要实现的目标并添加更多上下文代码?更具体一点,当你说没有单引号时,你指的是什么?
  • 如果您需要提取可以使用Object.values(object) 的对象值,例如在您的示例中,您可以尝试const values = Object.values(rates) 现在values 将包含此数组[ 0.75, 0.9, 109.44, 7.02, 0.98, 1.32 ]
  • 非常好.. 我尝试使用它,它工作得很好,但只在 console.log 内。我无法用 innerHTML 表达它。我会继续努力。非常感谢您的帮助。

标签: javascript html css arrays object


【解决方案1】:

你快到了:

const rates = {
  "UK Pounds": 0.75,
  "Euros": 0.9,
  "Yen": 109.44,
  "Yuan": 7.02,
  "Swiss Francs": 0.98,
  "Canadian Dollars": 1.32
}

function getCurrency() {
  let cur_type = document.getElementById('currencies').value.trim()
  let msg = cur_type ? "One US Dollar buys you " + rates[cur_type] + " " + cur_type : ""
  document.getElementById("exchangerate").innerHTML = msg
}
<h1>Currency Exchange Rates to US Dollar</h1>
<select id="currencies" onchange="getCurrency()">
  <option value="">Select a Currency</option>
  <option>UK Pounds</option>
  <option>Euros</option>
  <option>Yen</option>
  <option>Yuan</option>
  <option>Swiss Francs</option>
  <option>Canadian Dollars</option>
</select>
<p id="exchangerate"></p>

【讨论】:

  • 完美我的朋友。非常感谢帮助我澄清我难以理解的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 2022-01-02
  • 2021-11-13
  • 2014-05-24
  • 2012-04-12
  • 2018-09-12
相关资源
最近更新 更多