【问题标题】:How do I ensure an array has no null values?如何确保数组没有空值?
【发布时间】:2018-01-09 10:30:58
【问题描述】:

我想在提交表单之前测试我的数组(输入值)。

我的数组有值:

const fields = [
  this.state.workshopSelected,
  this.state.countrySelected,
  this.state.productionTypeSelected,
  this.state.numEmployeesSelected,
  this.state.startAt
];

我试过这个:

_.forEach(fields, (field) => {
  if (field === null) {
    return false;
  }
});

alert('Can submit !');
...

我认为我的问题是因为我没有使用 Promise。我尝试使用Promise.all(fields).then(()); 进行测试,但我总是在then

有人知道吗?

谢谢你:)

【问题讨论】:

  • 不,这与异步或承诺无关。
  • @Bergi:OP 使用的是lodash's _.forEach,而不是 Array 的。它确实允许通过return false 提前终止。
  • @T.J.Crowder 不过,_.forEach 不会像 OP 所期望的那样返回值或从函数中中断(以防止警报),是吗?
  • @Bergi:它确实破坏了_.forEach。它不会返回该信息,不。

标签: javascript asynchronous promise


【解决方案1】:

问题在于,即使您提前终止了lodash _.forEach 循环,您也不会else对您拥有null 条目的信息执行任何操作。

代替 lodash 的 _.forEach,我会使用内置的 Array#includes(相当新)或 Array#indexOf 来确定是否有任何条目是 null

if (fields.includes(null)) { // or if (fields.indexOf(null) != -1)
    // At least one was null
} else {
    // All were non-null
    alert('Can submit !');
}

对于更复杂的测试,您可以使用Array#some,它可以让您为测试提供回调。

indexOf 的实时示例:

const state = {
  workshopSelected: [],
  countrySelected: [],
  productionTypeSelected: [],
  numEmployeesSelected: [],
  startAt: []
};
const fields = [
  state.workshopSelected,
  state.countrySelected,
  state.productionTypeSelected,
  state.numEmployeesSelected,
  state.startAt
];
if (fields.indexOf(null) != -1) {
  console.log("Before: At least one was null");
} else {
  console.log("Before: None were null");
}
fields[2] = null;
if (fields.indexOf(null) != -1) {
  console.log("After: At least one was null");
} else {
  console.log("After: None were null");
}

【讨论】:

  • 谢谢@T.J.Crowder,我已经编辑了我的代码,它工作得很好,解释也很好。再次感谢!
【解决方案2】:

除非有异步操作(例如,如果您从服务器获取该数组),否则您不需要使用 Promise。

如果您已经拥有该数组,您可以执行以下操作:

// Using lodash/underscore
var isValid = _.every(fields, (field) => (field!==null)}

// OR using the Array.every method

var isValid = fields.every((field)=>(field!==null))

// Or using vanilla JS only
function checkArray(array){
   for(var i = 0; i < array.length ; i ++){
       if(array[i]===null){
           return false;
       }
   }
   return true;
}

var isValid = checkArray(fields);

// After you get that value, you can execute your alert based on it
if(!isValid){
    alert('Something went wrong..');
}

【讨论】:

    【解决方案3】:

    试试这个简单的 sn-p

    var isAllowedToSubmit = true;
    _.forEach(fields, (field) => {
      if (!field) {
        isAllowedToSubmit = false;
      }
    });
    
    if(isAllowedToSubmit)
     alert('Can submit !');
    

    【讨论】:

      【解决方案4】:

      你可以在没有库的情况下做到这一点:

      if (fields.some(field => field === null)) {
          alert('Cannot submit');
      } else {
          alert('Can submit');
      }
      

      【讨论】:

        【解决方案5】:

        你不需要使用 lodash,你可以用简单的 vanilla javascript 来做到这一点。只需遍历每个字段,如果发生错误,请将您的 errors bool 设置为 true

        let errors = false;
        fields.forEach(field) => {
          if(field === null || field === '') {
            errors = true;
          }
        });
        
        if (!errors) {
          alert('Yay no errors, now you can submit');
        }
        

        你可以使用 es6。

         const hasNoError = fields.every((field, index, selfArray) => field !== null);
         if (!hasNoError) {
            alert('yay It works');
         };
        

        查看 Array.every 文档Array every MDN documentation

        【讨论】:

        • Downvoter:不是最优的(还有 Adeel,你为什么要添加 field === ''?),但我不会 downvoted 它。毕竟它有效
        • 它有效,如果 OP 想要检查他/她的数组中的任何空值,则添加了 field === ''。我不知道为什么我被否决了。这种方法比使用 lodash 更好。
        猜你喜欢
        • 2012-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多