输入值与声明的数组中包含字符串的任何值相等/匹配

时间:2017-07-07 18:22:39

标签: javascript arrays input

我有这个JS代码,我需要将输入值与数组进行比较,如果输入值与数组中的某个值匹配则显示相关消息,但我无法获取数组值并进行比较他们的输入值。

var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

    if ($("input.reservationkey").val() === invalidkeyreservation) {
        BootstrapDialog.show(return $content;}




    } else{
        window.location.href = "/branches/Cancelaciones/Seleccion.html";
    }

4 个答案:

答案 0 :(得分:1)

这是 .indexOf() 的用途。



samples = [['A', 'B', 'D'],
           ['A', 'C', 'E'],
           ['A', 'C', 'D']]




答案 1 :(得分:1)

也许你想使用includes

var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if (invalidkeyreservation.includes($("input.reservationkey").val())) {
    BootstrapDialog.show(return $content;}
} else{
    window.location.href = "/branches/Cancelaciones/Seleccion.html";
}

Obs:如果你的目标是旧的浏览器,可以使用polyfill,或者只使用indexOf,如另一个答案中所示。

答案 2 :(得分:1)

你应该能够看到数组中的一个元素是否包含任何字符串值,如下所示:

ES6

const invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if(invalidkeyreservation.some(key => key === $("input.reservationkey").val()) {
    BootstrapDialog.show(return $content);
} else{
    window.location.href = "/branches/Cancelaciones/Seleccion.html";
}

ES5

var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if(invalidkeyreservation.indexOf($("input.reservationkey").val()) > -1) {
    BootstrapDialog.show(return $content);
} else{
    window.location.href = "/branches/Cancelaciones/Seleccion.html";
}

答案 3 :(得分:0)

尝试

var toCheck = $("input.reservationkey").val().trim().toUpperCase();
if (invalidkeyreservation.includes(toCheck )) {
 //your code with the condition
}

希望,这有帮助