繁体   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