减少许多||运营商的一个声明

时间:2016-05-27 08:41:36

标签: javascript jquery operators

我目前正在验证表单并检查以确保输入框不为空。为此,我使用下面定义的app.validation.empty()方法。在我的if陈述中,有很多重复。我怎么能把以下内容放入

if(!app.validation.empty(contestName) || !app.validation.empty(date) ||!app.validation.empty(month) ||!app.validation.empty(year) || !app.validation.empty(countryName) || !app.validation.empty(userName) || !app.validation.empty(userLastName))

进入一个方法,因此减少到一个语句?

2 个答案:

答案 0 :(得分:2)

您可以使用app.validation.empty作为回调Array#every

if (![contestName, date, month, year, countryName, userName, userLastName]
    .every(app.validation.empty)) {

答案 1 :(得分:1)

您可以在最新浏览器中使用 some() ES6 arrow function

if ([contestName, date, month, year, countryName, userName, userLastName].some((v) => !app.validation.empty(v)))

您甚至可以避免使用变量

app.sendForm = {
    init: function(){    
        $("#entry").submit(function( event ) {
            if(if (["#email","#first_name","#last_name","#birth_day","#birth_month","#birth_year","#contest1_name","#country",'#privacy_check'].some((v) => !app.validation.empty($(v))))){
                event.preventDefault();
                alert("There are errors with your form.");
            } else {
                alert("You have entered the competition.");
            }      
        });
    }
};