验证除0以外的数组序列值

时间:2016-09-10 17:31:49

标签: javascript arrays

我有一个数组验证值是否按降序排序。但是,如果序列的值为0,则会中断该过程并返回false而不是true。我如何避免0值并继续下降过程。 https://jsfiddle.net/snb3p0qy/1/

function customValidate(array) {
    var length = array.length;
    return array.every(function(value, index) {
        var nextIndex = index + 1;
        return nextIndex < length ? value >= array[nextIndex] : true;
    });
}
document.write(customValidate([1, 2, 3, 4, 5]));
document.write(customValidate([5, 0, 3, 2, 1]));//This supposed to be true
document.write(customValidate([0, 0, 0, 4, 5]));
document.write(customValidate([0, 0, 0, 2, 1]));

2 个答案:

答案 0 :(得分:3)

如果您希望继续使用every方法,可以在进行测试之前过滤掉0

function customValidate(array) {
  'use strict'
  return array.filter(item => item != 0).every(function(value, index, filteredArray) {
    // instead of referencing the original array the filtered
    // array that is pass as third argument to every is used
    var nextIndex = index + 1;
    return nextIndex < filteredArray.length ? value >= filteredArray[nextIndex] : true;
  });
}

但这种方法的缺点是你将创建一个新的临时数组。因此,对于大数据,这种方法不能很好地扩展。

更好的想法是使用常规循环来测试它。可能类似的东西(这肯定不是最好的代码):

function customValidate(array) {
 'use strict'
  var length = array.length;
  // set i to the index of the first value that is not 0
  var i = array.findIndex(value => value != 0); 
  var lastItem = array[i];

  i++;
  // after the first item was found, loop to the end of the list
  while (i < length) {
    // if the current item is not 0 then do the compare otherwise skip the test.
    if (array[i] != 0) {
      if (array[i] > lastItem) {
        return false;
      }
      lastItem = array[i];
    }
    i++;
  }
  return true;
}
目前并非所有浏览器都支持

Array.prototype.findIndex(),但您可以使用MDN网站上显示的polyfill,或者将其替换为循环。

编辑我在filter示例中遇到错误,因为过滤后的数组必须用作参考。

答案 1 :(得分:2)

尝试以下return语句

return nextIndex < length ? value === 0 || value >= array[nextIndex] : true;

甚至

return nextIndex >= length || value === 0 || value >= array[nextIndex];

因此我编辑了代码以使其适用于[5,0,1]场景但当然使用for循环会更好,如第二个答案

while (array[nextIndex] === 0 && nextIndex < length) {
    nextIndex++;
}
return nextIndex >= length || value === 0 || value >= array[nextIndex];
相关问题