验证数组的最后一个值是否大于先前的值 [英] Validate if the last value of array is greater than previous value

查看:151
本文介绍了验证数组的最后一个值是否大于先前的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array with value, [0,3,4,6,0], How do I validate if the before values is less than the after values?

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 。因此,我需要验证输入是否不按顺序排列。

I need to require the user to enter an ordered sequence of numbers like 5, 4, 3, 2, 1. Hence, I need to validate if the enter is not in an ordered sequence.

推荐答案

在ES5中使用 Array#every

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]));

这篇关于验证数组的最后一个值是否大于先前的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆