Get the index of the first element in an array with value greater than x

前端 未结 3 1040
有刺的猬
有刺的猬 2021-02-09 16:53

I have this array:

var array = [400, 4000, 400, 400, 4000];

How can I get the index of the first element with value greater than 400?

相关标签:
3条回答
  • 2021-02-09 17:06
    var array = [0, 0, 3, 5, 6];
    var x = 5;
    var i = 0;
    while (array[i] <= x) {
        i++;
    }
    
    0 讨论(0)
  • 2021-02-09 17:20

    You can use a simple for loop and check each element.

    var array = [400, 4000, 400, 400, 4000];
    
    var result;
    
    for(var i=0, l=array.length; i<l; i++){
      if(array[i] > 400){
        result = i;
        break;
      }
    }
    
    if(typeof result !== 'undefined'){
      console.log('number greater than 400 found at array index: ' + result);
    } else {
      console.log('no number greater than 400 found in the given arrry.');
    }

    Read up: for - JavaScript | MDN

    0 讨论(0)
  • 2021-02-09 17:26

    You can use findIndex here

    check this snippet

    var array = [400, 4000, 400, 400, 4000];
    var index=array.findIndex(function(number) {
      return number > 400;
    });
    console.log(index);

    0 讨论(0)
提交回复
热议问题