gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:39:03 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com