如何确保数组没有空值?

时间:2018-01-09 10:30:58

标签: javascript asynchronous promise

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

我的数组值:

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

有人有想法吗?

谢谢:)

5 个答案:

答案 0 :(得分:2)

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

我使用内置的Array#includes(相当新的)或Array#indexOf代替lodash的_.forEach来查找是否有任何条目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");
}

答案 1 :(得分:0)

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

如果您已经拥有该阵列,则可以执行以下操作:

// 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..');
}

答案 2 :(得分:0)

试试这个简单的代码段

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

if(isAllowedToSubmit)
 alert('Can submit !');

答案 3 :(得分:0)

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

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

答案 4 :(得分:-1)

您不需要使用lodash,您可以使用简单的vanilla javascript执行此操作。只需遍历每个字段,如果发生错误,请将errors布尔设置为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