2016-05-15 5 views
0
var array = ["ab", "cd", "ef", "ab", "gh"]; 

は今、私は位置0と私は唯一の位置3.上のインデックス要素を持ちたい3. "ab"を持って、私は私が唯一の3位にインデックス要素を取得できますか0の位置に"ab"をしたくないですか?助けてください。2つの同じ要素で配列のインデックス要素を取得するにはどうすればよいですか?


第2のオプション: 5個以上の要素がある場合はどうなりますか?このような:

var array = ["ab", "cd", "ef", "ab", "gh", "ab", "kl", "ab", "ab"];

と今私は、5位に要素を持っていたいですか?簡単な言葉では

var lastIndex = 0; 
var checkValue = 'ab'; 
var array = ["ab", "cd", "ef", "ab", "gh"]; 

for(var i = 0; i < array.length; i++){ 
    if(array[i] == checkValue) lastIndex = i; 
}; 

+0

をし、最初の値より大きい開始値 –

答えて

1

のは、これを試してみましょう

  • lastIndexは、最後のマッチング・インデックスが含まれている変数です。
  • checkValueは、配列で探している値です。
  • 配列全体のサイクルループで、実際の項目がチェック値と等しいかどうかを確認します。はいの場合は、lastIndex varを更新してください。
+0

Krystian:他のシナリオ/必要条件がある場合あなたの質問を更新することを検討してください(そうするために、タグの下にある「編集」リンクを使用してください)。そうすれば、すべての答えがあなたのすべての要件を満たすためのソリューションを提供しようとするか、または追加の要件に応じて、それらがなぜ不可能か薦められないのかを説明します。 –

0

私は配列

var array = ["ab", "cd", "ef", "ab", "gh"]; 
 

 
function search(search, arr, callback) { 
 
    for (var i = 0; i < arr.length; i++) { 
 
    if (search === arr[i]) { 
 
     callback(arr[i], i, arr); 
 
    } 
 
    } 
 
    return -1; 
 
} 
 

 
search('ab', array, function(item, i) { 
 
    alert(item + " : " + i); 
 
}); 
 

 
// or use this 
 

 
Array.prototype.search = function(search, callback) { 
 
    for (var i = 0; i < this.length; i++) { 
 
    if (search === this[i]) { 
 
     callback(this[i], i, this); 
 
    } 
 
    } 
 
    return -1; 
 
}; 
 

 
array.search('ab', function(item, i) { 
 
    alert(item + " : " + i); 
 
});

0

から何かを検索することができます機能を集約している私がお勧めしたい:lastIndexOf` `とや` indexOf`と

function findAll (needle, haystack) { 

    // we iterate over the supplied array using 
    // Array.prototype.map() to find those elements 
    // which are equal to the searched-for value 
    // (the needle in the haystack): 
    var indices = haystack.map(function (el, i) { 
     if (el === needle) { 
      // when a needle is found we return the 
      // index of that match: 
      return i; 
     } 
    // then we use Array.prototype.filter(Boolean) 
    // to retain only those values that are true, 
    // to filter out the otherwise undefined values 
    // returned by Array.prototype.map(): 
    }).filter(Boolean); 

    // if the indices array is not empty (a zero 
    // length is evaluates to false/falsey) we 
    // return that array, otherwise we return -1 
    // to behave similarly to the indexOf() method: 
    return indices.length ? indices : -1; 
} 

var array = ["ab", "cd", "ef", "ab", "gh"], 
     needleAt = findAll('ab', array); // [0, 3] 
関連する問題