Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Javascript中找到数组中小于x的第一个元素?_Javascript_Arrays - Fatal编程技术网

如何在Javascript中找到数组中小于x的第一个元素?

如何在Javascript中找到数组中小于x的第一个元素?,javascript,arrays,Javascript,Arrays,我有一个问题,我想循环一个从大到小的数组,并将数组中的数字与提供的x进行比较 我的代码应该是这样的: function convertToRoman(num) { var decimalNum = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; while (num > 0){ // to prevent the number from reaching zero for (var k = 0; k <

我有一个问题,我想循环一个从大到小的数组,并将数组中的数字与提供的x进行比较

我的代码应该是这样的:

function convertToRoman(num) {

  var decimalNum = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];

  while (num > 0){ // to prevent the number from reaching zero
    for (var k = 0; k < decimalNum.length; k++) { //to loop through the array

    if(num > decimalNum[k]) {return k}; //this is the part in which I wanted to return the element that is next in the array that is less than the num
    }
  }


}

convertToRoman(36);
例如,如果num=36,那么数组中小于36的下一个数字将是10。所以我想返回10。我该怎么做


我试图在网上找到解决方案,但我发现的唯一解决方案是java或C++,完全不同于JavaScript,对吗?我不认为也应该使用二进制搜索…

因为你应该得到值而不是索引

功能转换器{ var decimalNum=[100090050040010090504010,9,5,4,1]; //当num>0时{//以防止数字达到零 对于var k=0;kdecimalNum[k]{ 返回小数位数[k] };//这是我想要返回数组中下一个小于num的元素的部分 } // } }
console.logconvertToRoman36 这是一个在IE中工作的解决方案,不管数组中的值是如何排序的

var lesser = decimalNum.filter(function(dec) {
  return dec < num;
});
var result = Math.max.apply(null, lesser);
如果您知道小数数组的排序方式与代码中的排序方式相同,则只需将Math.max部分替换为较小的[0]

返回值,而不是您所在的索引:

函数转换器{ var数组=[10009005004001009050,40,10,9,5,4,1]; 对于变量i=0;iarray[i]{//如果当前项小于参数 return数组[i];//返回您所在索引处的值 }; } }
console.logconvertToRoman36//返回10return arr.findel=>el