Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  139] [ 7]  / answers: 1 / hits: 120292  / 11 Years ago, tue, april 30, 2013, 12:00:00

I am trying to make a JavaScript function that will search an array of strings for a value and return the next string. For example, if an array is built such that an item is followed by its stock code, I want to search for the item and have the stock code written.



var item = (from user input); //some code to get the initial item from user
function findcode(code){
var arr = [ball, 1f7g, spoon, 2c8d, pen, 9c3c]; //making the array
for (var i=0; i<arr.lenth; i++){ //for loop to look through array
arr.indexOf(item); //search array for whatever the user input was
var code = arr(i+1); //make the variable 'code' whatever comes next
break;
}
}
document.write(code); //write the code, I.e., whatever comes after the item


(I'm sure it's obvious I'm new to JavaScript, and while this is similar to a number of other questions I found, those seemed to have more involved arrays or more complex searches. I can't seem to simplify them for my needs.)


More From » arrays

 Answers
22

You've almost got it right, but the syntax is arr[x], not arr(x):



index = array.indexOf(value);
if(index >= 0 && index < array.length - 1)
nextItem = array[index + 1]


BTW, using an object instead of an array might be a better option:



data = {ball:1f7g, spoon:2c8d, pen:9c3c}


and then simply



code = data[name]

[#78516] Monday, April 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hugo

Total Points: 21
Total Questions: 120
Total Answers: 107

Location: Belarus
Member since Tue, Jul 20, 2021
3 Years ago
;