简体   繁体   English

javascript indexOf无法按预期使用数组

[英]javascript indexOf not working as expected with array

I am getting -1 from myarray.indexOf(element) even when element appears to be in myarray.即使元素出现在 myarray 中,我也会从myarray.indexOf(element)获得 -1。

Here's some code snippets:以下是一些代码片段:

function createChangeRecord( old_array, new_array ) {
    var nds = new_array.slice(0,new_array.length);
    var el, idx;
    if (...) {
        ...
    } else if ( old_array.length==new_array.length ) {
        for ( var i=0; i<old_array.length; i++ ) {
            el = old_array[i];
            idx = nds.indexOf(el);
            if ( idx!=(-1) ) {
                ...
            } else {
                var a = "el: " + el + "; nds: " + nds + "; nds.indexOf(el): " + nds.indexOf(el);
                alert( a );
                ...
            }
        }
        ...
    }
    ...
}

The alert shows me that nds does indeed contain el but the alert should only fire when idx==-1, which should only be true when nds does not contain el.警报显示 nds 确实包含 el,但警报仅应在 idx==-1 时触发,仅当 nds 不包含 el 时才应为真。

I know I haven't given enough information to determine the specific issue in my case, but maybe someone can tell me some general reasons which might cause this behavior?我知道我没有提供足够的信息来确定我的案例中的具体问题,但也许有人可以告诉我一些可能导致这种行为的一般原因?

Responses to a similar question suggested using jQuery inArray() instead of indexOf, but I want to know why indexOf doesn't work.对类似问题的回答建议使用 jQuery inArray() 而不是 indexOf,但我想知道为什么 indexOf 不起作用。 Others suggested that indexOf is for strings, not arrays, but that's not true from the online docs I can find.其他人建议 indexOf 用于字符串,而不是数组,但我可以找到的在线文档不是这样。

Use利用

nds.indexOf(parseInt(el,10)) 

where nds is an array and el is a number (or supposed to be a number)其中nds是一个数组, el是一个数字(或应该是一个数字)

Edit:编辑:

From msdn :来自msdn

JavaScript is a loosely typed language, which means you do not declare the data types of variables explicitly. JavaScript 是一种松散类型的语言,这意味着您无需显式声明变量的数据类型。 In many cases JavaScript performs conversions automatically when they are needed.在许多情况下,JavaScript 在需要时会自动执行转换。 For example, if you add a number to an item that consists of text (a string), the number is converted to text.例如,如果您向包含文本(字符串)的项目添加数字,则该数字将转换为文本。

And I guess such conversion was the reason of indexOf returning -1 because one of your array contained number and other contained string.我猜这种转换是indexOf返回-1的原因,因为您的数组之一包含数字和其他包含的字符串。

For example:例如:

old_array = ["10", "20", "30"];
new_array = [10, 20, 30];

Below is my attempt to answer your questions:以下是我尝试回答您的问题:

Why indexOf() does not work?为什么 indexOf() 不起作用?

It does work and I guess it worked in your case too.它确实有效,我想它也适用于你的情况。 It returned -1 when el string, eg "100" , was not found in an array of numbers, eg nds=[100,200] which is true.当在数字数组中找不到el字符串(例如"100" )时,它返回-1 ,例如nds=[100,200]这是真的。 Because "100" string is not same as 100 number.因为"100"字符串与100数字不同。

Does indexOf() work with strings, array, etc? indexOf() 是否适用于字符串、数组等?

Yes, indexOf() works with array (of number, string, or any object), as well as with string.是的, indexOf()适用于数组(数字、字符串或任何对象)以及字符串。 But you have to make sure to check with same types.但是你必须确保检查相同的类型。

What does parseInt() do? parseInt() 是做什么的?

To avoid unintended comparison of a number with a string, we can use parseInt() , for example parseInt("123", 10) returns the number 123 .为了避免数字与字符串的意外比较,我们可以使用parseInt() ,例如parseInt("123", 10)返回数字123

The second argument 10 is called radix .第二个参数10称为radix A number (from 2 to 36) that represents the numeral system to be used.表示要使用的数字系统的数字(从 2 到 36)。

Summary:概括:

> "javascript is awesome".indexOf('v')
2
> [10, 20, 30].indexOf("20")
-1
> [10, 20, 30].indexOf(20)
1
> [10, 20, 30].indexOf( parseInt("20", 10) ) 
1
> typeof (100)
number
> typeof ("100")
string
> typeof( parseInt( "100", 10))
number
> parseInt( "100", 10)
100
> parseInt("100", 2)
4
> parseInt(11.3, 10)
11
> parseInt(11.3, 2)
3
> [10.3, 11.3, 12.3, 11].indexOf( parseInt(11.3, 10) )
3

To see all of above in action:要查看以上所有内容:

check the below code snippet but be aware of alert();检查下面的代码片段,但要注意alert(); and console.log();console.log(); when you run it.当你运行它时。

 function createChangeRecord( old_array, new_array ) { var nds = new_array.slice( 0, new_array.length ); // this seems to be redundant var el, idx, msg; if ( old_array.length == new_array.length ) { for ( var i=0; i<old_array.length; i++ ) { el = old_array[i]; idx = nds.indexOf(el); if ( idx != -1 ) { msg = "Found: el: " + el + "; nds: " + nds + "; nds.indexOf(el): " + idx + "\n typeof el: " + (typeof el) + "; typepf nds[" + i + "]: " + (typeof nds[i]); } else { msg = "Not Found: el: " + el + "; nds: " + nds + "; nds.indexOf(el): " + idx + "\n typeof el: " + (typeof el) + "; typepf nds[" + i + "]: " + (typeof nds[i]); } console.log( msg ); alert( msg ); } } else { var err = 'Array lengths are not same'; console.log( err ); alert( err ); } } // this will work var old_array_g = [ 10, 20 ]; var new_array_g = [ 10, 20 ]; createChangeRecord( old_array_g, new_array_g ); // this will not work var old_array_g = [ "10", "20" ]; var new_array_g = [ 10, 20 ]; createChangeRecord( old_array_g, new_array_g ); // Yes: indesOf works with strings too var withStrings = "'javascript is awesome'.indexOf('v'): " + "javascript is awesome".indexOf('v'); console.log( withStrings ); alert( withStrings ); // parseInt() returns a number or say integer var usingParse = "typeof(123): " + typeof( 123 ) + "; typeof( parseInt('123', 10) ): " + typeof ( parseInt('123', 10) ) + "; typeof ('123'): " + typeof('123'); console.log( usingParse ); alert( usingParse ); // parseInt() with base 2 var parseBase2 = "parseInt( '100', 2 ): " + parseInt('100', 2) + "; parseInt( '100' , 10): " + parseInt('100', 10); console.log( parseBase2 ); alert( parseBase2 );

indexOf does work and does do what you say it does. indexOf确实有效,并且按照您所说的去做。

For example (to demonstrate from a console):例如(从控制台演示):

> a = [1,2,3,4,5,6,7,8];
  [1, 2, 3, 4, 5, 6, 7, 8]
> b = a.slice(0,a.length);
  [1, 2, 3, 4, 5, 6, 7, 8]
> b.indexOf(a[4])
  4

If you're getting this error, it might mean you've mixed up source and destination (the array before the dot is the one being searched), or you have another subtle programming error (like you aren't comparing the array you think you're comparing).如果您收到此错误,则可能意味着您混淆了源和目标(点之前的数组是正在搜索的数组),或者您有另一个微妙的编程错误(就像您没有比较您认为的数组你在比较)。

When you use indexOf( value ) on an Array, it returns you the index of the value in the array.在数组上使用 indexOf( value ) 时,它会返回数组中索引

> var testArray = ["a","b","c"];
> testArray.indexOf(1)
-1
> testArray.indexOf("b")
1
> testArray.indexOf("c")
2
> testArray = [10,12,3];
> testArray.indexOf(12)
1

You should check what you get from el with a typeof( el )你应该用 typeof( el ) 检查你从el得到的东西

Taking the top example:以最上面的例子:

where you have idx=nds.indexOf(el)你有idx=nds.indexOf(el)

replace it with idx=nds.indexOf(''+el+'')将其替换为idx=nds.indexOf(''+el+'')

It solved a similar problem for me within the thing I'm working on, but I stumbled on it messing around looking for a solution.它在我正在做的事情中为我解决了一个类似的问题,但我偶然发现它正在四处寻找解决方案。

Whether it's stable in all circumstances is something I can't answer.我无法回答它是否在所有情况下都稳定。

If your search array contained numbers, and you want to search for items like 2 or "2"如果您的搜索数组包含数字,并且您想要搜索2"2"类的项目

nds = [1, 2, 3, 4, 5];

This works (Add plus)这有效(加加)

nds.indexOf(+el)

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

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