【发布时间】: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