[英]find index of array element in another array javascript
I've 2 1-D arrays like this: 我有2个这样的一维数组:
var words = ['Habitat for Humanity', 'Caring', 'Helping', 'People', 'Safety', 'Security', 'Shelter', 'Community', 'Volunteering'];
var sources = ['Helping', 'Community', 'Caring', 'Safety', 'Security'];
I want to find out the index of an element taken from the 'sources' array in the 'words' array. 我想找出取自'words'数组中'sources'数组的元素的索引。 For example, the element 'Helping' in the 'sources' array is located at index 2 in 'words' array.
例如,“源”数组中的元素“帮助”位于“单词”数组中的索引2处。 So I need "2" as my solution when I search for index of the word "Helping".
因此,当我搜索“帮助”一词的索引时,我需要使用“ 2”作为解决方案。 Can somebody help me on this?
有人可以帮我吗? Thanks.
谢谢。
I tried using 'indexOf' function in arrays but id didn't work and when I searched for similar questions, it's been said that it'll not work in this problem. 我尝试在数组中使用'indexOf'函数,但id无效,当我搜索类似的问题时,据说它在此问题中不起作用。
Yes, indexOf will do the job. 是的,indexOf将完成这项工作。 Check:
校验:
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]
You can use an each
function. 您可以使用
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;
}
Answered From mobile. 从手机回答。 Feel free to format.
随时格式化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.