如何检查数组中的特定项是否有值?Javascript

How to check whether specific items inside an array have a value? Javascript

本文关键字:是否 Javascript 何检查 检查 数组      更新时间:2023-09-26

我有一个从元素中获取值的函数:

function getTransactionValues() {
    var o = {};
    o.reservations        = [];
    $('#custom-headers option:selected').each(function (i, selected) {
        o.reservations[i] = $(selected).val();
    });
    o.amount              = $('input[name=amount-price]').val();
    o.currency_value      = $('input[name=currency-value]').val();
    o.currency_name       = $('.currency_appendto option:selected').html();
    o.actual_amount       = $('input[name=actual-amount]').val();
    o.actual_remaining    = $('input[name=actual-remaining]').val();
    o.funds_arrival_date  = $('input[name=funds-arrival]').val();
    o.paid_to             = $('.paidto option:selected').html();
    o.checkbox            = $('.multi-transaction:checked').map(function () {
        return this.value
    }).get();
    return o;
}

现在我想检查金额、实际金额和资金到达日期是否填写完毕。如果是,我将从按钮中释放禁用的类。我试过

    var check_review = function () {
    var a = getTransactionValues();
    var options = [a.amount, a.actual_amount, a.funds_arrival_date];
    for(i = 0; i < options.length; i++) {
        if(options[i].length > 0) {
            $('a[name=review_button]').removeClass('disabled');
        }
        else{
            //this array is empty
            alert('There is a problem!');
        }
    }
}
$('.test').click(function() {
    check_review();
});

但它似乎不起作用。。

是否使用JQuery删除禁用的属性?

你能看看上面的链接吗,我认为我们应该使用$('.inputDisabled').prop("disabled",false);

即使单个数组元素不是空的,代码也会从a中删除类disabled。要确保数组的所有元素都不是空的,然后只想删除类,方法是:

for(i = 0; i < options.length; i++) {
        if(options[i].length > 0) {
            $('a[name=review_button]').removeClass('disabled');
        }
        else{
            $('a[name=review_button]').addClass('disabled');
        }
    }

或者另一种方式是

var check = true;
for(i = 0; i < options.length; i++) {
        if(options[i].length == 0) {
            check = false;
        }
    }
if(check ) $('a[name=review_button]').removeClass('disabled');

尝试使用Array.prototype.every()

if (options.every(Boolean)) {
  $("a[name=review_button]").removeClass("disabled");
} else {
  // do other stuff
}