我需要返回最接近零的元素的位置而不是负数。
我有4个卷尺寸(以英寸为单位)来切割胶片。我正在尝试输入宽度变量并从数组元素中减去,最接近0将返回最佳卷尺寸的数组位置。我希望这是有道理的。谢谢。
var width = ""
var rollArray = [36, 48, 60, 72]
var newArray = []
for(i in rollArray){ newArray.push ((rollArray[i]) - width) }
alert(newArray);
返回宽度减去每个元素,现在我需要找到如何返回最低值数组位置,以便我可以从等效的rollArray位置获取卷大小。
答案 0 :(得分:3)
var width = 41;
var rollArray = [36, 48, 60, 72];
var closest = rollArray.filter(function(ele){return ele-width >= 0}).sort()[0];
答案 1 :(得分:0)
var width = ""
var rollArray = [36, 48, 60, 72]
var newArray = []
var min=1000000 //a very large number that you know it's larger than (rollArray[i]) - width)
var minIndex=-1
for (var i=0; i<rollArray.length; i++){ newArray.push ((rollArray[i]) - width)
if (min< rollArray[i]) - width & rollArray[i]) - width >0)
{
min = rollArray[i]) - width;
minIndex = i;
}
}
alert (minIndex);
alert(newArray);
答案 2 :(得分:0)
var width = 37;
var rollArray = [36, 48, 60, 72];
var closest = null;
for (var i=0; i<rollArray.length; i++)
{
if (rollArray[i] >= width)
{
if (closest == null || rollArray[i] <= rollArray[closest])
{
closest = i;
}
}
}