简体   繁体   English

如何在jQuery插件中表示数据集?

[英]How to represent set of data in jQuery plug-in?

I am writing my first jQuery plug-in to do unit conversion. 我正在编写我的第一个jQuery插件来进行单位转换。 It's a fairly straightforward plug-in in that I take the original value, a unit I want to convert from and a unit I want to convert to (as strings, for now). 这是一个非常简单的插件,它采用原始值,要从中转换的单位和要转换成的单位(目前为字符串)。

As part of this library, however, I want to be able to know which units I can convert. 但是,作为该库的一部分,我希望能够知道可以转换的单位。 When I did this in F#, I could use discriminated unions to represent the types, and then have a "master" discriminated union which held each one of those types. 当我在F#中执行此操作时,我可以使用区分的联合来表示类型,然后使用“主”区分的联合来容纳这些类型中的每一个。 This allowed me to work with units as one type and ensure it was typesafe (for example, I couldn't convert Grams to Meters). 这使我可以将单位作为一种类型使用,并确保它是类型安全的(例如,我无法将Grams转换为Meters)。

How would I go about doing something like this in JavaScript? 我将如何在JavaScript中执行类似的操作? I figured I will need to use JSON to represent all the types I can convert between (maybe not?), but I don't know if I entirely understand how to do something like this. 我认为我将需要使用JSON表示我可以在其之间转换的所有类型(也许不是吗?),但是我不知道我是否完全理解如何做这样的事情。 I would appreciate a starting point so I can continue researching and learning. 我希望有一个起点,这样我才能继续研究和学习。 Thank you. 谢谢。

You could create an array like this: 您可以创建一个像这样的数组:

var conversions = {
    meters: {
        conversion: 1,
        unit: "length"
    },
    feet: {
        conversion: 1 / 3.28, // 1 foot is about a third of a meter
        unit: "length"
    },
    kilograms: {
        conversion: 1,
        unit: "weight"
    },
    pounds: {
        conversion: 1 / 2.204,
        unit: "weight"
    }
}

Then all you have to do is make sure that what you're converting to has the same unit as what you're converting from. 然后,您要做的就是确保要转换的内容与要转换的内容具有相同的单位。 Each type of unit maps onto its value in SI units (eg. all length units will convert to meters), so that you can go from any unit of one type to any other. 每种类型的单位都以SI单位映射到其值(例如,所有长度单位都将转换为米),因此您可以从一种类型的任何单位转换为其他任何单位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM