Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 数组中搜索的索引_Javascript_Arrays - Fatal编程技术网

Javascript 数组中搜索的索引

Javascript 数组中搜索的索引,javascript,arrays,Javascript,Arrays,我的代码: currentName = "Black"; const bannedItems = [ "Green", "Yellow", "Black", "White" ]; 当我在控制台中键入此命令时,得到False: (currentName.indexOf(bannedItems) != -1); 但当我尝试这一点时,我明白了: (currentName.indexOf("Black") != -1); 这意味着我不能用数组来做这个?我现在就是这样做的,我觉得还有更优雅的方式

我的代码:

currentName = "Black";

const bannedItems = [
"Green",
"Yellow",
"Black",
"White"
];
当我在控制台中键入此命令时,得到False:

(currentName.indexOf(bannedItems) != -1);
但当我尝试这一点时,我明白了:

(currentName.indexOf("Black") != -1);
这意味着我不能用数组来做这个?我现在就是这样做的,我觉得还有更优雅的方式

if ((currentName.indexOf("Green") != -1 || currentName.indexOf("Yellow") != -1 || currentName.indexOf("Black") != -1 || currentName.indexOf("White") != -1)) return;

只需交换
bannditems
currentName

bannditems.indexOf(当前名称)

方法
indexOf
是字符串和数组固有的。


您的
currentName.indexOf(“Black”)
返回
true
,因为字符串“Black”确实包含字符串“Black”。

变量的正确顺序:

bannedItems.indexOf(currentName) != -1

有两种不同的
indexOf
方法

String.indexOf(substring)
Array.indexOf(array_member)
您正在使用前者。它在您正在搜索的字符串中查找
子字符串中指定的字符串

“黑色”
出现在字符串
“黑色”

“绿、黄、黑、白”
(这是将数组转换为字符串时得到的结果)不会出现在字符串
“黑”

如果要在数组中搜索字符串
“Black”
,则需要调用数组的
indexOf
方法:

bannedItems.indexOf(currentName) != -1
indexOf()方法返回字符串中指定值第一次出现的位置。

如果要搜索的值从未出现,则此方法返回-1


注意:indexOf()方法区分大小写。

您真正想要实现什么?但是如果currentName是:var currentName=“Test | Black”;然后它将返回False。我想检查是否有来自BanndItems数组的单词currentName@Alue-然后需要依次测试(例如,使用
forEach
)数组中的每个单词
String.indexOf
只接受一项测试。