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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

You 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