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

时间:2013-04-30 07:50:03

标签: 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

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

5 个答案:

答案 0 :(得分:46)

你差不多了,但语法是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]

答案 1 :(得分:3)

我认为对象可能是这种任务的更好的数据结构

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


console.log(items['ball']); // 1f7g

答案 2 :(得分:2)

循环数组中的项可能有用

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

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

答案 3 :(得分: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

答案 4 :(得分:0)

尝试使用此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"

这是您的用法:

getTotalTimeValues()