[英]Check whether any of multiple values exists in an array
(This question has been changed a bit since some of the answers were posted. That is why they might seem a bit off-topic and/or out of context) (自从发布了一些答案以来,这个问题已经有所改变。这就是为什么它们看起来可能有点偏离主题和/或脱离上下文的原因)
Hello! 你好! So basically, I have this string that is entered by a user (a caption for an image, for example), and an array of links/words that I want to "block" the user from entering.
因此,基本上,我有一个由用户输入的字符串(例如,图像标题),以及一个我要“阻止”用户输入的链接/单词数组。 (This would be to prevent from swearing, advertising etc.)
(这是为了防止发誓,广告等)
So I need some code that checks whether a certain value exists in an array. 因此,我需要一些代码来检查数组中是否存在某个值。
This is my array: 这是我的数组:
var blockedUrls = ["https://google.com", "https://facebook.com"]
and this is the values I want to check 这是我要检查的值
var userInput = "Hello! Check out my cool facebook profile at https://facebook.com";
(This would normally be set to a value fetched from an input of some sort, the static text is just to simplify) (通常将其设置为从某种输入中获取的值,静态文本只是为了简化)
So this is what I have tried: 所以这就是我尝试过的:
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}]`);
}
});
So a summary: How do I check if any of multiple values exists in an array? 总结一下:如何检查数组中是否存在多个值?
You can check if a value is in an array by using indexOf
您可以使用
indexOf
检查值是否在数组中
var value = document.getElementById('myFile').value;
if (unAllowedLinks.indexOf(value) != -1) {
// value is in array
}
-1
is returned when the value is not found in the array, else it returns the index of the value. 如果在数组中找不到该值,则返回
-1
,否则返回该值的索引。
If you want to be able to change the number of values in unAllowedLinks
you'd be better off using indexOf() , like so: 如果您希望能够更改
unAllowedLinks
中值的数量,最好使用indexOf() ,如下所示:
function updateImage() {
if (unAllowedLinks.indexOf(document.getElementById('myFile').value) > -1) {
alert("This link is reserved");
} else {
// Use the value
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.