簡體   English   中英

在另一個數組javascript中找到數組元素的索引

[英]find index of array element in another array javascript

我有2個這樣的一維數組:

var words = ['Habitat for Humanity', 'Caring', 'Helping', 'People', 'Safety', 'Security', 'Shelter', 'Community', 'Volunteering'];
var sources = ['Helping', 'Community', 'Caring', 'Safety', 'Security'];

我想找出取自'words'數組中'sources'數組的元素的索引。 例如,“源”數組中的元素“幫助”位於“單詞”數組中的索引2處。 因此,當我搜索“幫助”一詞的索引時,我需要使用“ 2”作為解決方案。 有人可以幫我嗎? 謝謝。

我嘗試在數組中使用'indexOf'函數,但id無效,當我搜索類似的問題時,據說它在此問題中不起作用。

是的,indexOf將完成這項工作。 校驗:

var words = ['Habitat for Humanity', 'Caring', 'Helping', 'People', 'Safety', 'Security', 'Shelter', 'Community', 'Volunteering'];
var sources = ['Helping', 'Community', 'Caring', 'Safety', 'Security'];

sources.forEach(function(source){
console.log(source, 'is at position', words.indexOf(source));
});

 var words = ['Habitat for Humanity', 'Caring', 'Helping', 'People', 'Safety', 'Security', 'Shelter', 'Community', 'Volunteering']; var sources = ['Helping', 'Community', 'Caring', 'Safety', 'Security']; sources.forEach(function(source){ document.getElementsByTagName('div')[0].innerHTML += source + ' is at position: ' + words.indexOf(source) + '<br>'; }); 
 <div></div> 

sources.map(function(word) { return words.indexOf(word); })
// => [2, 7, 1, 4, 5]

您可以使用each功能。

$.each(words, function(key, value) {
      if(value == 'Helping'){
          alert(key);
      }
});
var searchArray=function(value,words){
var result=-1;
for(var i=0;i<words.length;i++){
if(words[i]==value){
result=i;break
}
return result;
}

從手機回答。 隨時格式化。

暫無
暫無

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

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