Javascript:通用获取数组中的下一项 [英] Javascript: Generic get next item in array
问题描述
我正在尝试创建一个 JavaScript 函数,它将在字符串数组中搜索一个值并返回下一个字符串.例如,如果构建了一个数组,使得一个项目后跟其股票代码,我想搜索该项目并写入股票代码.
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.)
推荐答案
你几乎猜对了,但语法是 arr[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, using an object instead of an array might be a better option:
data = {"ball":"1f7g", "spoon":"2c8d", "pen":"9c3c"}
然后简单地
code = data[name]
这篇关于Javascript:通用获取数组中的下一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!