javascript indexOf が配列で期待どおりに動作しない 質問する

javascript indexOf が配列で期待どおりに動作しない 質問する

myarray.indexOf(element)要素が myarray 内にあるように見えても、-1 が返されます。

以下にコード スニペットをいくつか示します。

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 が含まれていない場合にのみ true になるはずです。

私のケースの具体的な問題を特定するには情報が不十分であることは承知していますが、この動作を引き起こす可能性のある一般的な理由を教えていただける方はいらっしゃいますか?

同様の質問への回答では、indexOf の代わりに jQuery inArray() を使用することが提案されていますが、indexOf が機能しない理由を知りたいです。他の人は、indexOf は配列ではなく文字列用であると示唆していますが、私が見つけたオンライン ドキュメントではそれは正しくありません。

ベストアンサー1

使用

nds.indexOf(parseInt(el,10)) 

ここでndsは配列であり、elは数値(または数値であるはずのもの)です。

編集:

からmsdn:

JavaScript は緩い型付けの言語です。つまり、変数のデータ型を明示的に宣言する必要はありません。多くの場合、JavaScript は必要なときに自動的に変換を実行します。たとえば、テキスト (文字列) で構成される項目に数値を追加すると、数値はテキストに変換されます。

そして、配列の 1 つに数値が含まれ、他の配列に文字列が含まれていたために、このような変換indexOfが返された理由だと思います。-1

例えば:

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

以下はあなたの質問に対する私の回答です:

indexOf() が機能しないのはなぜですか?

これは動作しますし、あなたのケースでも動作すると思います。文字列 (例) が数値の配列 (例 ) 内に見つからない-1場合(これは true) が返されます。文字列は数値と同じではないためです。el"100"nds=[100,200]"100"100

indexOf() は文字列や配列などでも機能しますか?

はい、indexOf()文字列だけでなく、配列(数値、文字列、または任意のオブジェクト)でも動作します。ただし、同じ型で確認する必要があります。

parseInt() は何をしますか?

数値と文字列の意図しない比較を回避するには、 を使用できますparseInt()。たとえば、parseInt("123", 10)は数値 を返します123

2番目の引数10基数使用する数値システムを表す数値 (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 );

おすすめ記事