如何在数组中获取具有两个相同元素的索引元素?

时间:2016-05-15 09:58:03

标签: javascript arrays

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位有元素吗?

3 个答案:

答案 0 :(得分:1)

让我们试试这个:

17:55:43

简单来说:

  • 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是您在数组中寻找的值;
  • 整个数组中的for循环,并检查实际项是否等于检查值。如果是,请更新checkValue var。

答案 1 :(得分:0)

我有一个可以从数组中搜索任何内容的函数

select convert(varchar(12), DATEADD(MONTH, 9, DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(MONTH, -9, GETDATE())), 0)), 101) as StartYear

答案 2 :(得分:0)

我建议:

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]