jak jak - 1 year ago 88
Javascript Question

Javascript: Generic get next item in array

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
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.)


Answer Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download