使用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