Javascript:Generic获取数组中的下一个项目

jak*_*jak 17 javascript arrays

我正在尝试创建一个JavaScript函数,它将搜索字符串数组中的值并返回下一个字符串.例如,如果构建一个数组使得项目后面跟着它的股票代码,我想搜索该项目并写入股票代码.

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
Run Code Online (Sandbox Code Playgroud)

(我确信很明显我是JavaScript的新手,虽然这与我发现的其他一些问题相似,但这些问题似乎涉及更多的数组或更复杂的搜索.我似乎无法简化它们.需要).

geo*_*org 52

你几乎把它弄好了,但语法arr[x]不是arr(x):

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

顺便说一句,使用对象而不是数组可能是更好的选择:

data = {"ball":"1f7g", "spoon":"2c8d", "pen":"9c3c"}
Run Code Online (Sandbox Code Playgroud)

然后简单地说

code = data[name]
Run Code Online (Sandbox Code Playgroud)

  • +1只是添加,[`Array.indexOf`是ES5](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf)并不适用于旧版浏览器. (2认同)

Ser*_*zN1 29

从数组循环项目这可能有用

const currentIndex = items.indexOf(currentItem);
const nextIndex = (currentIndex + 1) % items.length;
items[nextIndex];
Run Code Online (Sandbox Code Playgroud)

第一项将从最后一项之后从数组的开头开始

  • 喜欢骑行时的“% items.length”技巧——漂亮又干净。 (2认同)
  • 较短:`const nextIndex = ++currentIndex % items.length` (2认同)