使用Javascript數組(或對象)的單位轉換器

[英]Unit Converter using Javascript arrays (or objects)


I'm building a unit converter on Javascript. What I want to do is store or pre-define all the unit values in an array like this:

我正在使用Javascript構建單元轉換器。我想要做的是在數組中存儲或預定義所有單位值,如下所示:

var converter_table = {
    'mass' : {
        'kilogram' : 1000,
        'gram' : 1,
        'ounce' : .035274,
        'pound' : .00220462
    },

    'length' : {
        'kilometer' : 1000,
        'meter' : 1
    }
};

And then be able to pull out the values and make calculations based on user input. For instance:

然后能夠提取值並根據用戶輸入進行計算。例如:

var quantity = 25, 
    category = 'mass',
    from_unit = 'kilogram',
    to_unit = 'pound';


var result = quantity * converter_table.category.from_unit * converter_table.category.to_unit;

alert(result);

Except, of course, converter_table.category.from_unit is undefined. Is there a way to pull this off?

當然,除了converter_table.category.from_unit之外,還沒有定義。有沒有辦法解決這個問題?

1 个解决方案

#1


2  

You can use array notation:

您可以使用數組表示法:

var result = quantity * converter_table[category][from_unit] * converter_table[category][to_unit];

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/10/09/a82a62bf49a88b88b847cc06719dd9d.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com