29

我正在尝试制作一个 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

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

4

5 回答 5

65

你几乎做对了,但语法是arr[x],不是arr(x)

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

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

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

然后简单地

code = data[name]
于 2013-04-30T07:52:00.000 回答
34

数组中的循环项目,这可能很有用

const currentIndex = items.indexOf(currentItem);
const nextIndex = (currentIndex + 1) % items.length;
items[nextIndex];

第一项将在最后一项之后从数组的开头获取

于 2019-02-19T15:50:49.170 回答
2

我认为对于此类任务,对象可能是更好的数据结构

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


console.log(items['ball']); // 1f7g
于 2013-04-30T07:56:11.793 回答
1

试试这个String.prototype功能:

String.prototype.cycle = function(arr) {
  const i = arr.indexOf(this.toString())
  if (i === -1) return undefined
  return arr[(i + 1) % arr.length];
};

以下是你如何使用它:

"a".cycle(["a", "b", "c"]); // "b"
"b".cycle(["a", "b", "c"]); // "c"
"c".cycle(["a", "b", "c"]); // "a"
"item1".cycle(["item1", "item2", "item3"]) // "item2"

如果你想反过来做,你可以使用这个Array.prototype函数:

Array.prototype.cycle = function(str) {
  const i = this.indexOf(str);
  if (i === -1) return undefined;
  return this[(i + 1) % this.length];
};

以下是你如何使用它:

["a", "b", "c"].cycle("a"); // "b"
["a", "b", "c"].cycle("b"); // "c"
["a", "b", "c"].cycle("c"); // "a"
["item1", "item2", "item3"].cycle("item1") // "item2"
于 2019-03-29T23:31:00.237 回答
0

您可以将数组作为参数传递给函数并从函数返回找到的值:

var item = "spoon"; // from user input
var arr = ["ball", "1f7g", "spoon", "2c8d", "pen", "9c3c"]; //making the array
function findcode(item, arr){
    var idx = arr.indexOf(item);  //search array for whatever the user input was
    if(idx >=0 && idx <= arr.length - 2) { // check index is in array bounds
        return arr[i+1]; // return whatever comes next to item
    }
    return '';
}
document.write(findcode(item, arr)); //write the code, i.e., whatever comes after the item
于 2013-04-30T08:00:19.757 回答