使用Javascript:通用获得数组下一个项目 [英] Javascript: Generic get next item in array

查看:81
本文介绍了使用Javascript:通用获得数组下一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个Javascript功能,将搜索字符串数组的值,并返回下一个字符串。例如,如果一个数组是建立这样一个项目后面是其股价code,我想搜索的项目,并有股票code写的。

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

(我敢肯定,很明显我是新来的Javascript,虽然这是类似一些,我发现其他问题,那些似乎有更多的参与阵列或更复杂的搜索,我似乎不能简化他们对我的需要。)

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

谢谢!

推荐答案

您已经几乎得到了它的权利,但语法是改编[X] ,而不是 ARR(X)

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,使用对象而不是数组的可能是一个更好的选择:

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

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

,然后简单地

code = data[name]

这篇关于使用Javascript:通用获得数组下一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆