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