Javascript 检查字符串中的数组元素

Javascript 检查字符串中的数组元素,javascript,Javascript,我一直在做“数组中的字符串检查”,但从来没有做过oposite。这就是我现在需要的。目前我有: var Hash = 'http://example.com/place/england, arr = ['/place/']; if(Hash.indexOf(arr)) { alert('it is') } else { alert('it is not') }; 问题是,它总是返回true(警报它是)。这里哪里出错了?我们只接受字符串作为参数,而您要传递一个数组。访问

我一直在做“数组中的字符串检查”,但从来没有做过oposite。这就是我现在需要的。目前我有:

var Hash = 'http://example.com/place/england,
    arr = ['/place/'];

if(Hash.indexOf(arr)) {
    alert('it is')
} else {
    alert('it is not')
};
问题是,它总是返回true(警报
它是
)。这里哪里出错了?

我们只接受字符串作为参数,而您要传递一个数组。访问数组的第一个元素以获取字符串,或者在整个数组上循环(如果它可能有多个元素)

if(Hash.indexOf(arr[0])) {
//                 ^^^ access first element
或循环整个阵列:

for(var i=0; i<arr.length; i++){
    if(Hash.indexOf(arr[i])) {
        alert('it is')
    } else {
        alert('it is not')
    };
}
for(var i=0;i在未找到时返回
-1
,在找到时返回
0…n-1
。因此,您说
['/place/']时是
。toString()
(其计算结果为
/place/
)不在字符串的开头;只有在第空位置找到时,才会得到
它不是

相反,您希望测试
-1
。此外,如果您希望测试数组的所有元素,而不是数组的串联(因为,如果
arr=['/place/','/time/']
,您将搜索字符串
“/place/,/time/”
),您需要执行其他操作,如迭代或正则表达式

// iteration (functional style)
var found = arr.some(function(element) { return Hash.indexOf(element) !== -1; });


escapeRegExp
from)

您需要在数组中循环以进行比较。其次,您的条件没有以所需的方式写入

if(Hash.indexOf(arr)) 
.indexOf()
为未找到的其他
-1
提供
-1
。在js
中,0
而其他数字为
,因此您总是会得到真警报

var-Hash=http://example.com/place/england',
arr=['/place/'];
var i=阵列长度;
而(我--)
if(-1
if(Hash.indexOf(arr))