简体   繁体   中英

Javascript function indexOf returns incorrect results

I have these two arrays:

array1 = ["a,1", "b,2", "c3", "d4", "e5", "f6"];
array2 = [1, 2, 3, 4];

And I'm trying to find out if an element of the first array is in the second one.

for (i = 0; i < array1.length; i++) { 
  if(array2.indexOf(array1[i][1]) != -1) {
    console.log('In array: '+array1[i][1]);
  } else {
    console.log('NOT in array: '+array1[i][1]);
}

In this case, I always get the message NOT in array .. .

But if I modify the code this way:

for (i = 0; i < array1.length; i++) { 
  if(array2.indexOf(1) != -1) {
    console.log('In array: '+array1[i][1]);
  } else {
    console.log('NOT in array: '+array1[i][1]);
}

The output is In array: ... .

With a number as a parameter of the indexOf() function it's working, but no with the variable... how is that possible?

Thank you

In your code:

if(array2.indexOf(array1[i][1]) != -1) {

is comparing a string to a number using strict comparison per the algorithm for indexOf . Also, in most cases you are comparing the wrong character from array1 . In:

"a,1"

character 1 is the comma, not the number. What you need to do is get the numbers from the strings in array1 , convert them to number type so indexOf works using an expression like:

+array1[i].replace(/\D/g,'')

then do the comparison, eg:

array1 = ["a,1", "b,2", "c3", "d4", "e5", "f6"];
array2 = [1, 2, 3, 4];


for (var i=0, iLen=array1.length; i<iLen; i++) {
    if (array2.indexOf(+array1[i].replace(/\D/g,'')) != -1) {
        console.log('In array: ' + array1[i]);
    } else {
        console.log('Not in array: ' + array1[i]);
    }
}

// In array: a,1
// In array: b,2
// In array: c3
// In array: d4
// Not in array: e5
// Not in array: f6

You may need to modify the regular expression getting the numbers depending on the full range of strings that might be in array1 .

An alternative is to convert the members of array2 to strings and search for them in the members of array1 .

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