提问者:小点点

验证数组的最后一个值是否大于前一个值


我有一个带值的数组,[0,3,4,6,0],如果前值小于后值,如何验证?

var array = [0,3,4,6,0];
for(var i = 0; i < array.length; i++){
   //if the value of 0 >,3 >,4, > 6
   //return false;
}

我需要要求用户输入有序的数字序列,例如5、4、3、2、1。因此,我需要验证输入是否不在有序序列中。


共3个答案

匿名用户

ES5中使用Array#的可能解决方案

function customValidate(array) {
  var length = array.length;
  return array.every(function(value, index) {
    var nextIndex = index + 1;
    return nextIndex < length ? value <= array[nextIndex] : true;
  });
}
console.log(customValidate([1, 2, 3, 4, 5]));
console.log(customValidate([5, 4, 3, 2, 1]));
console.log(customValidate([0, 0, 0, 4, 5]));
console.log(customValidate([0, 0, 0, 2, 1]));

匿名用户

迭代所有数组,期望为true,直到达到false,您可以在其中跳出循环。

function ordered(array) {
  var isOk = true; // Set to true initially

  for (var i = 0; i < array.length - 1; i++) {
    if (array[i] > array[i + 1]) {
      // If something doesn't match, we're done, the list isn't in order
      isOk = false;
      break;
    }
  }
  document.write(isOk + "<br />");
}

ordered([]);
ordered([0, 0, 0, 1]);
ordered([1, 0]);
ordered([0, 0, 0, 1, 3, 4, 5]);
ordered([5, 0, 4, 1, 3, 4]);

匿名用户

        function inOrder(array){

            for(var i = 0; i < array.length - 1; i++){

                if((array[i] < array[i+1]))
                    return false;

            }
            return true;
        }