使用JavaScript从最接近给定数字的字典中的键中获取值 [英] Getting the value from key in a dictionary that is nearest to a given number using JavaScript
本文介绍了使用JavaScript从最接近给定数字的字典中的键中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一本字典(键是整数,值是浮点数).我现在要向字典查询键的值,该键的值>>大于给定数字,但<比下一个更大的键更重要.
I have a dictionary (keys are integers, values are float). I would now ask the dictionary for the value of the key that is > than the given number but < than the next greater key.
示例:
dict = {100:0.0035,150:0.0024,200:0.0019}.
dict = {100: 0.0035, 150: 0.0024, 200: 0.0019}.
我给122,应该给我0.0035
i give 122, it should give me 0.0035
我给333,应该给我0.0019
i give 333, it should give me 0.0019
我给200,它应该给我0.0024
i give 200, it should give me 0.0024
谢谢!
推荐答案
工作示例(在Firefox 3.6下测试):
Working example (tested under Firefox 3.6):
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var dict = {100: 0.0035, 150: 0.0024, 200: 0.0019};
function r(aNum) {
var result;
for (var key in dict) {
var dist = key - aNum
if ((dist < 0 && dist < result) || result === undefined) {
result = key;
}
}
return dict[result];
}
$(document).ready(function() {
$('li').each(function() {
var id = $(this).attr('id').replace('n', '')
$(this).html(id + ": " + r(id));
});
});
</script>
</head>
<body>
<ul>
<li id="n122"></li>
<li id="n333"></li>
<li id="n200"></li>
</ul>
</body>
</html>
这篇关于使用JavaScript从最接近给定数字的字典中的键中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文