javascript indexOf 无法按预期使用数组

标签 javascript arrays indexof

我从 myarray.indexOf(element) 得到 -1,即使 element 似乎在 myarray 中。

下面是一些代码片段:

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 );
                ...
            }
        }
        ...
    }
    ...
}

警报告诉我 nds 确实包含 el,但警报应该只在 idx==-1 时触发,只有当 nds 不包含 el 时才会触发。

我知道我没有提供足够的信息来确定我的案例中的具体问题,但也许有人可以告诉我一些可能导致此行为的一般原因?

对类似问题的回答建议使用 jQuery inArray() 而不是 indexOf,但我想知道为什么 indexOf 不起作用。其他人建议 indexOf 适用于字符串,而不是数组,但从我能找到的在线文档来看,情况并非如此。

最佳答案

使用

nds.indexOf(parseInt(el,10)) 

其中 nds 是一个数组,el 是一个数字(或者应该是一个数字)

编辑:

来自 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.

而且我猜这种转换是 indexOf 返回 -1 的原因,因为您的数组之一包含数字,而另一个包含字符串。

例如:

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

以下是我尝试回答您的问题:

为什么 indexOf() 不起作用?

它确实有效,我想它也适用于您的情况。 当 el 字符串(例如 "100")在数字数组中找不到时,它返回 -1,例如nds=[100,200] 这是真的。因为 "100" 字符串与 100 数字不同。

indexOf() 是否适用于字符串、数组等?

是的,indexOf() 适用于数组(数字、字符串或任何对象)以及字符串。但是你必须确保检查相同的类型。

parseInt() 是做什么的?

为了避免数字与字符串的意外比较,我们可以使用 parseInt(),例如 parseInt("123", 10) 返回数字 123

第二个参数 10 称为 radix。表示要使用的数字系统的数字(从 2 到 36)。

总结:

> "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

要查看以上所有操作:

检查下面的代码片段,但在运行时注意 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 );

关于javascript indexOf 无法按预期使用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14222791/

相关文章:

C 以十六进制值初始化数组

javascript - TypeError: undefined 不是 "indexOf"上的函数?

javascript - 将 Fineuploader 与 ASP.NET 网络表单一起使用。对严格模式调用函数的访问被审查

javascript - IE10 上的 WebSocket 给出安全错误

javascript - 如何在 Angular 中用当前时间减去 firebase 时间戳并检查它是否超过 5 分钟

javascript - 使用 javascript 循环对象并将结果放入数组

javascript - React,数组中的图像未显示在 <img src> 中

java - 如何找到数组中变化最大的差异? - java

javascript - 查找数组中数组元素的索引

Java 第一次找到一个特定的字母