javascript - 如何获取javascript对象中的值编号?

标签 javascript html css arrays object

我正在为货币兑换示例构建一个 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.
  }
}

最佳答案

你快到了:

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>

关于javascript - 如何获取javascript对象中的值编号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59359889/

相关文章:

javascript - Next.js动态路由错误: The provided path `page-name` does not match the page: `/[slug]`

javascript - JQuery 可搜索下拉框

html - 带有字体图标的按钮的辅助功能

javascript - 如何创建输入 id 的数组

css - 造型单选按钮

Jquery DateTimePicker 不使用 CSS 显示

javascript - 为什么在 Vue 中使用 $refs 时有时需要 $el?

javascript - 如何将参数从js文件传输到HTML中的javascript?

html - 为什么后续 block 元素的框从前一个 block 元素的内容而不是前面元素的边框开始?

javascript - 仅当屏幕小于屏幕时才在屏幕底部显示 div