簡體   English   中英

如何獲得具有兩個相同元素的數組中的索引元素?

[英]How to get index element in array with two the same elements?

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

現在,我在位置0和3上具有"ab" 。我只希望在位置3上具有索引元素。我不希望在位置0上具有"ab" 。如何僅在位置3上獲得索引元素? 請幫忙。


第二種選擇:如果我有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;
};

簡單來說:

  • lastIndex是包含最后一個匹配索引的變量;
  • checkValue是您要在數組中尋找的值;
  • for循環遍歷整個數組,並檢查實際項是否等於檢查值。 如果是,請更新lastIndex

我有可以從數組中搜索任何內容的函數

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

我建議:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM