[英]How to get index element in array with two the same elements?
var array = ["ab", "cd", "ef", "ab", "gh"];
Now, i have "ab"
on position 0 and 3. I want to have index element only on position 3. I don't want "ab"
on position 0. How can i get index element only on position 3? 现在,我在位置0和3上具有
"ab"
。我只希望在位置3上具有索引元素。我不希望在位置0上具有"ab"
。如何仅在位置3上获得索引元素? Please help. 请帮忙。
second option: what if i have 5 elements or more? 第二种选择:如果我有5个或更多元素怎么办? like this:
像这样:
var array = ["ab", "cd", "ef", "ab", "gh", "ab", "kl", "ab", "ab"];
and now i want to have element on position 5? 现在我想在位置5上添加元素?
Let's try this: 让我们尝试一下:
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;
};
In simple word: 简单来说:
lastIndex
is the variable that contains the last matching index; lastIndex
是包含最后一个匹配索引的变量; checkValue
is the value you are looking for in the array; checkValue
是您要在数组中寻找的值; lastIndex
var. lastIndex
。 I have maked function that can search anything from array 我有可以从数组中搜索任何内容的函数
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); });
I'd suggest: 我建议:
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.