简体   繁体   中英

Javascript IndexOf on an element of an Array

I have a JavaScript Array called arrTemp.

I want to search arrTemp[1] to see if it contains the character '|'

I have tried the following:

var arrValue = arrTemp[1].split(",");
if(arrValue.indexOf('|') > -1) {
    alert(arrValue);
}

but it says the method indexOf is not supported for this type.

Is there an alternate method I can achieve this??

Split returns an array, so you need to loop through that array.

var arrValue = arrTemp[1].split(",");

for(var i = 0; i < arrValue.length; i++){
    if(arrValue[i].indexOf('|') > -1)
    {
       alert(arrValue[i]);
    }
}

if you just want to see if arrTemp[1] contains | then you don't even need the split:

if(arrTemp[1].indexOf('|') > -1) {
    alert(arrValue);
}

Or if you want to see if an entry in the split array is equal to '|', eg in the string foo,|,bar as opposed to foo,x|x,bar then you can do:

var arrValue = arrTemp[1].split(",");
for(var i = 0; i < arrValue.length; i++){
    if(arrValue[i] == '|')
    {
       alert(arrValue[i]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM