我有一个收藏品。藏品如下
X=[1940,1941,1943,1945,1978]
我想通过传递一些值(ex:1944.578895)从上面的集合中找到最近的值。
对于1944.57889
,它将返回1945
,对于1943.5
,它将像那样返回1943
。集合"**X
**"将发生变化,这意味着它也包含浮点数。
因此,我希望找到浮点集合和数字集合的最近值。
谢谢,
锡瓦
发布于 2013-04-29 06:48:25
Javascript中的所有数字都是浮点数,所以这应该很好:
var theArray = [1940,1941,1943,1945,1978];
var goal = 1944.578895;
var closest = null;
$.each(theArray, function(){
if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) {
closest = this;
}
});
发布于 2013-04-29 06:48:35
您可以使用Math.abs
Math.abs(this - goal) < Math.abs(closest - goal)
有关@Guffa的完整示例,请参阅以下内容:
using jquery, how would i find the closest match in an array, to a specified number
https://stackoverflow.com/questions/16272714
复制相似问题