字典等效数据结构? [英] Dictionary equivalent data structure?

查看:137
本文介绍了字典等效数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript,并希望保留一个设定的km / mph近似值的列表。 (我无法以编程方式转换,我正在使用一种期望某些值的外部API,所以它确实必须是一个字典等价物。)

I'm working in JavaScript and want to keep a list of set km/mph approximations to hand. (I can't convert programmatically, I'm working with an external API that expects certain values, so it really does have to be a dictionary equivalent.)

目前我'使用对象:

var KM_MPH = { 10: 16, 12: 20, 15: 24 };

从mph到km是很容易的:

Going from mph to km is pretty easy:

var km = KM_MPH[10];

如何找到mph,给定km?另外,对象是JavaScript中用于此类事物的最佳数据结构?我更习惯Python。

How do I find mph, given km? Also, is an object the best data structure to use for this sort of thing in JavaScript? I'm more used to Python.

推荐答案

一个基本的JavaScript对象其实是最好的选择。要找到一个反向映射,你可以这样做:

A basic JavaScript object is in fact the best choice here. To find a reverse mapping, you can do:

function mphToKM(val){
    for(var km in KM_MPH){
        if(KM_MPH[km] === val){
            return km;
        } 
    }

    return null;
}

或者,如果您预计需要做很多查找,我会推荐具有第二个JS对象,即第一个

Or, if you anticipate having to do a lot of lookups, I would recommend having a secondary JS Object that is the mirror of the first

var mph_km = {};
for(var km in KM_MPH){
    mph_km[KM_MPH[km]] = km;
}

// mph_km[16] ==> 10

我不知道你是否真的这样做,以每小时公里到几英里每小时...如果是这样,直接进行转换似乎更有意义,而不是依赖于值的哈希映射。

I don't know if you are in fact doing this for conversion between kilometres per hour to miles per hour... if so, it seems to make more sense to just do the conversion directly instead of relying on a hash mapping of the values.

var conversionRate = 1.609344; // kilometres per mile
function kphToMPH(val){
    return val / conversionRate ;
}

function mphToKPH(val){
    return val * conversionRate;
}

这篇关于字典等效数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆