javascript indexOf 无法按预期使用数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14222791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript indexOf not working as expected with array
提问by baixiwei
I am getting -1 from myarray.indexOf(element)even when element appears to be in myarray.
myarray.indexOf(element)即使元素出现在 myarray 中,我也得到 -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. Others suggested that indexOf is for strings, not arrays, but that's not true from the online docs I can find.
对类似问题的回答建议使用 jQuery inArray() 而不是 indexOf,但我想知道为什么 indexOf 不起作用。其他人建议 indexOf 用于字符串,而不是数组,但从我可以找到的在线文档来看,情况并非如此。
回答by Ajeet Shah
Use
用
nds.indexOf(parseInt(el,10))
where ndsis an array and elis a number (or supposed to be a number)
wherends是一个数组并且el是一个数字(或者应该是一个数字)
Edit:
编辑:
From msdn:
从msdn:
JavaScript is a loosely typed language, which means you do not declare the data types of variables explicitly. In many cases JavaScript performs conversions automatically when they are needed. For example, if you add a number to an item that consists of text (a string), the number is converted to text.
JavaScript 是一种松散类型语言,这意味着您无需显式声明变量的数据类型。在许多情况下,JavaScript 会在需要时自动执行转换。例如,如果向由文本(字符串)组成的项目添加数字,则该数字将转换为文本。
And I guess such conversion was the reason of indexOfreturning -1because 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 -1when elstring, e.g "100", was not found in an array of numbers, e.g. nds=[100,200]which is true. Because "100"string is not same as 100number.
它确实有效,我想它也适用于您的情况。-1当el字符串,例如"100",在数字数组中找不到时返回,例如nds=[100,200]这是真的。因为"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. But you have to make sure to check with same types.
是的,indexOf()适用于数组(数字、字符串或任何对象)以及字符串。但是您必须确保使用相同的类型进行检查。
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 10is called radix. A number (from 2 to 36) that represents the numeral system to be used.
第二个参数10称为基数。一个数字(从 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();and console.log();when you run it.
检查下面的代码片段,但要注意的alert();和console.log();当你运行它。
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 );
回答by Plynx
indexOfdoes 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).
如果您收到此错误,则可能意味着您混淆了源和目标(点之前的数组是正在搜索的数组),或者您有另一个微妙的编程错误(就像您没有比较您认为的数组你在比较)。
回答by Finickyflame
When you use indexOf(value) on an Array, it returns you the indexof the valuein the array.
当您使用的indexOf(值上的阵列),它返回你的索引的的值在数组中。
> 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 elwith a typeof(el)
你应该用 typeof( el)检查你从el得到什么
回答by Howard
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.
它是否在所有情况下都稳定是我无法回答的。
回答by user2511140
If your search array contained numbers, and you want to search for items like 2or "2"
如果您的搜索数组包含数字,并且您想搜索类似2或"2"
nds = [1, 2, 3, 4, 5];
This works (Add plus)
这有效(添加加号)
nds.indexOf(+el)

