gpt4 book ai didi

javascript:从数组转换货币的干净方法

转载 作者:行者123 更新时间:2023-11-28 13:31:41 25 4
gpt4 key购买 nike

各位!目前我已经编写了下面的代码,它将一种货币转换为另一种货币,但问题是我在 switch block 中逐一定义每种货币,

如果我有 100 种货币要转换,那么我必须编写 100 个 switch case我可以使下面的代码动态且简短吗?

var currencies = {};

$(document).ready(function(){
yahoo_getdata();
});
function yahoo_getdata() {
var a = new Date();
var b = "http://someAPIurl.com/webservice/v1/symbols/allcurrencies/quote?format=json&random=" + a.getTime() + "&callback=?";
$.getJSON(b, function (e) {
if (e) {
var i, l, r, c;
r = e.list.resources;
for (i = 0, l = r.length; i < l; i += 1) {
c = r[i].resource.fields;
//console.log(c.name, c.price);
switch (c.name) {
case "USD/EUR":
currencies.EUR = c.price;
console.log('USD/EUR = ' + c.price);
break;
case "USD/USD":
currencies.USD = c.price;
console.log('USD/USD = ' + c.price);
break;
case "USD/JPY":
currencies.JPY = c.price;
console.log('USD/JPY = ' + c.price);
break;
case "USD/INR":
currencies.INR = c.price;
console.log('USD/INR = ' + c.price);
break;
}
}
console.log(currencies);
//console.log(e);
//var d = {};
}
});

}

$("#amount1").keyup(function() {
var
usd,
amount1 = $('#amount1').val(),
currency1 = $("#currency1").val(),
currency2 = $("#currency2").val();

// normalize to USD
usd = amount1 / currencies[currency1];

// convert to target currency
$('#amount2').val(usd * currencies[currency2]);
});

最佳答案

使用将货币名称映射到对象属性名称的对象:

var currency_map = {
'USD/EUR': 'EUR',
'USD/USD': 'USD',
'USD/JPY': 'JPY',
...
};

然后:

for (var i = 0, l = r.length; i < l; i++) {
c = r[i].resource.fields;
currencies[currency_map[c.name] || c.name] = c.price;
console.log(c.name + ' = ' + c.price);
}

FIDDLE

关于javascript:从数组转换货币的干净方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24301166/

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