[英]how to get index of array in javascript
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? 如何获得该指数?
You might want to avoid this altogether and use the String
object's indexOf
method: 您可能希望完全避免这种情况,并使用String
对象的indexOf
方法:
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 (" "); 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. 确保打开萤火虫以查看结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.