简体   繁体   English

JavaScript函数indexOf返回不正确的结果

[英]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: ... . 输出为In数组:...。

With a number as a parameter of the indexOf() function it's working, but no with the variable... how is that possible? 使用数字作为indexOf()函数的参数,它可以工作,但不能使用变量...这怎么可能?

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 . 根据indexOf算法,使用严格比较将字符串与数字进行比较。 Also, in most cases you are comparing the wrong character from array1 . 另外,在大多数情况下,您正在比较array1的错误字符。 In: 在:

"a,1"

character 1 is the comma, not the number. 字符1是逗号,而不是数字。 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的字符串中获取数字,将它们转换为数字类型,以便indexOf使用如下表达式进行工作:

+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 . 您可能需要修改正则表达式以获取数字,具体取决于array1中可能包含的所有字符串。

An alternative is to convert the members of array2 to strings and search for them in the members of array1 . 一种替代方法是将array2的成员转换为字符串,然后在array1的成员中搜索它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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