我想制作一个过滤器。如果您输入“黑名单”中的单词,它会告诉您某些内容。我已经获得了所有代码但是有问题。
JS:
input = document.getElementById("input").value;
array = ["1","2","3"];
function filter() {
if (input == array)
// I will do something.
} else {
// Something too
}
}
如果input
是array
中的项目,我想这样做。声明是真的。但是这样做的正确方法是什么?因为我在这里做的事不起作用! 我也希望摆脱区分大小写!如果数组中包含hello
,则会检测到hello
和Hello
。
很抱歉,如果之前有人问这个问题。我搜索了它,但不知道要使用哪些关键字。
编辑1:
我正在改变我的问题: 我想查看原始问题中的内容,但还有其他一些功能。
我还想检查input
中array
是否包含项目的一部分。因此,如果输入为hello
,则helloworld
被检测到,因为其中包含hello
。以及hello
或Hello
。
答案 0 :(得分:6)
使用indexOf
:
if (array.indexOf(input) > -1)
如果元素不包含在数组中,则为-1。
答案 1 :(得分:1)
此代码应该有效:
input = document.getElementById("input").value;
array = ["1","2","3"];
function filter() {
if (array.indexOf(input) >= 0)
// I will do something.
} else {
// Something too
}
}
indexOf方法是数组类型的成员,返回搜索到的元素的索引(从0开始),如果找不到元素,则返回-1。
答案 2 :(得分:0)
我认为你在寻找is
input = document.getElementById("input").value;
array = ["1","2","3"];
function filter() {
if (array.indexOf(input) !== -1 )
// I will do something.
} else {
// Something too
}
}