民间!
目前我已经写了下面的代码,它将一种货币转换成另一种货币,但问题是我正在定义每种货币。 switch
区块中的每种货币一个接一个,
如果我要转换100种货币,那么我必须写100个开关案例 有没有我可以使下面的代码动态和简短?
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]);
});
答案 0 :(得分:5)
使用将货币名称映射到对象属性名称的对象:
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);
}