我该如何干掉这段代码?

时间:2017-04-10 04:45:34

标签: javascript foreach

我想迭代formProps对象并检查键并将相同键上的值设置到errors对象上。

if (!formProps.email) {
    errors.email = "Please enter an email"
}
if (!formProps.password) {
  errors.password = "Please enter a password"
}
if (!formProps.passwordConfirm) {
  formProps.passwordConfirm = "Please enter a password confirmation"
}
if (formProps.password != formProps.passwordConfirm) {
  errors.password = "Passwords must match"
}

1 个答案:

答案 0 :(得分:0)

这样可以更好地发送数组,因为您可以同时显示所有错误

var errors = [];
!formProps.email ? errors.push("Please enter an email") : null;
!formProps.password ? errors.push("Please enter a password") : null;
!formProps.passwordConfirm ? errors.push("Please enter a password confirmation") : null;
formProps.password != formProps.passwordConfirm ? errors.push("Passwords must match") : null;
if(errors.length > 0){
    return errors;
}