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

标签 javascript jquery yahoo-finance

各位! 目前我已经编写了下面的代码,它将一种货币转换为另一种货币,但问题是我在 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/

相关文章:

JavaScript 对象 - 数字键文字未定义

javascript - 仅在 EmberJS 中实现多个 promise 后才执行代码

javascript - iframe 中的 jquery 搜索

javascript - jquery/js 中添加按钮时出错

javascript - Jquery - 如何将变量传递到函数中以供使用?

iphone - 以编程方式按日期访问雅虎财经的货币汇率

javascript - Webpack,新 block 正在以错误的路径加载

java雅虎财经API不返回历史数据

c - 如何使用 libcurl (或其他方式)从 HTTP 服务器检索文件?

javascript - 如何比较嵌套数组中的父记录和子记录?