admin管理员组文章数量:1389892
I have a problem in obtaining the index, if in an array there are some similar words but with a different index position and when I select one of the word, the index that I get is not from words but from which I select the same word in previous position
for example I have a sentence:
The Harvest is the process of gathering
the bold word is the word that I choose..
this is my code:
var str = "The Harvest is the process of gathering";
var myArray = str.split ("");
var Select = "the";
and I have a function like this:
function getIndex (arrayItem, item) {
for (var x = 0; x <arrayItem.length; x + +) {
if (arrayItem [x] == item) {
return x;
}
}
return -1;
}
var idx = getIndex (myArray, Select);
how to get that index?
I have a problem in obtaining the index, if in an array there are some similar words but with a different index position and when I select one of the word, the index that I get is not from words but from which I select the same word in previous position
for example I have a sentence:
The Harvest is the process of gathering
the bold word is the word that I choose..
this is my code:
var str = "The Harvest is the process of gathering";
var myArray = str.split ("");
var Select = "the";
and I have a function like this:
function getIndex (arrayItem, item) {
for (var x = 0; x <arrayItem.length; x + +) {
if (arrayItem [x] == item) {
return x;
}
}
return -1;
}
var idx = getIndex (myArray, Select);
how to get that index?
Share Improve this question asked Nov 4, 2010 at 4:08 user495688user495688 9632 gold badges15 silver badges26 bronze badges2 Answers
Reset to default 5You might want to avoid this altogether and use the String
object's indexOf
method:
var str = "The Harvest is the process of gathering";
var idx = str.indexOf('the');
Just to point out, fix this one line in your code and you should get what you are looking for
var myArray = str.split (" "); //instead of splitting it character by character, split it where spaces appear. That should get the correct result. Your quotes don't have a space, hence the results you are getting. link text
Check out code here . Make sure to have firebug on to see the results.
本文标签: how to get index of array in javascriptStack Overflow
版权声明:本文标题:how to get index of array in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744566781a2613097.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论