我有一个这样的数组:
var bookCh = {'TOMSAWYER':[Twain,50],
'PARELANDRA':[Lewis,150],
'ROGUECODE':[Russinovich,23],
'WRINKLE':[Lengle,12]};
如果我在ROGUECODE上匹配某些东西,我想打印控制台的下一个键(例如,如果我匹配ROGUECODE,则打印WRINKLE)。这是我必须做的匹配,但我不知道如何打印数组中的下一个键而不是当前的键。如果它们是数字键,那显然很容易,但它们不是......
var currentBook = "ROGUECODE";
for (var bookKey in bookCh) {
if (bookKey == currentBook) {
console.log("Next book: " + ???);
}
}
答案 0 :(得分:1)
声明你的数组是这样的
var bookCh = [
{
'id': 'TOMSAWYER',
'meta': [Twain, 50]
},
{
'id': 'PARELANDRA',
'meta': [Lewis, 150]
},
{
'id': 'ROGUECODE',
'meta': [Russinovich, 23]
},
{
'id': 'WRINKLE',
'meta': [Lengle, 12]
}
]
现在当你迭代它时
for(var i=0; i<bookCh.length-1; i++) {
// bookCh[i+1] (this is next array item)
}
答案 1 :(得分:0)
var currentBook = "ROGUECODE";
var keys = Object.keys(bookCh);
for (var bookKey in bookCh) {
if (bookKey == currentBook) {
var curIdx = keys.indoxOf(bookKey);
var nextBookKey = curIdx < keys.length-1 ? keys[curIdx+1] : null;
console.log("Next book: " + nextBookKey);
}
}
答案 2 :(得分:0)
我想到一种愚蠢的方式......如果你的钥匙很少......
var bookCh = {
'TOMSAWYER': ['Twain', 50],
'PARELANDRA': ['Lewis', 150],
'ROGUECODE': ['Russinovich', 23],
'WRINKLE': ['Lengle', 12]
};
var currentBook = "ROGUECODE";
var order = {
'TOMSAWYER': 'PARELANDRA',
'PARELANDRA': 'ROGUECODE',
'ROGUECODE': 'WRINKLE',
'WRINKLE': 'TOMSAWYER'
};
for (var bookKey in bookCh) {
if (bookKey == currentBook) {
console.log("Next book: " + bookCh[order[bookKey]]);
}
}
&#13;