检查数组中是否存在多个值中的任何一个

时间:2017-06-27 20:43:33

标签: javascript html

(由于一些答案已经发布,这个问题已经有所改变。这就是为什么它们可能看起来有点偏离主题和/或脱离背景)

您好!所以基本上,我有一个用户输入的字符串(例如图像的标题),以及我想“阻止”用户输入的链接/单词数组。 (这可以防止咒骂,广告等。)

所以我需要一些代码来检查数组中是否存在某个值。

这是我的阵列:

var blockedUrls = ["https://google.com", "https://facebook.com"]

这是我要检查的值

var userInput = "Hello! Check out my cool facebook profile at https://facebook.com";

(这通常会设置为从某种输入中获取的值,静态文本只是为了简化)

所以这就是我的尝试:

let values = userInput.split(" ");
values.forEach((i, value) => {
    // inArray is a made-up-function in order to better explain my intention
    // The function I need here is a function that can check whether the value of the "value" variable exists in the "blockedUrls" array.
    if(value.inArray(blockedUrls)) {
        return alert(`You can't say that word! [${value}]`);
    }
});

总结:如何检查数组中是否存在多个值?

2 个答案:

答案 0 :(得分:5)

您可以使用indexOf

检查数值是否在数组中
var value = document.getElementById('myFile').value;
if (unAllowedLinks.indexOf(value) != -1) {
    // value is in array
}
在数组中找不到值时返回

-1,否则返回值的索引。

答案 1 :(得分:1)

如果您希望能够更改unAllowedLinks中的值数量,最好使用indexOf(),例如:

function updateImage() {
    if (unAllowedLinks.indexOf(document.getElementById('myFile').value) > -1) {
        alert("This link is reserved");
    } else {
        // Use the value
    }
};
相关问题