在执行搜索以定位特定项目的索引后,我试图返回给定数组中的下一个项目。
我有以下代码可以定位索引,但它无法返回下一个值
var myArray = [{"id" : "51fcd6fcf22d94c881000005","creator" : true},
{"id" : "5244abaa0c11b3da22000012","creator" : false},
{"id" : "52027f4354c8a8fd33000008","creator" : false}]
function nextElement(id) {
var i = myArray.length;
while( i-- ) {
if(myArray[i].id == id) break;
}
console.log(i) <-- This returns '0' which is correct
console.log(myArray[i++%myArray.length]); <-- This returns the object value at 0 too
};
nextElement('51fcd6fcf22d94c881000005')
什么不起作用是当我运行函数时它返回我传递给函数的对象
我希望能够将一个 ID 传递给函数并返回下一项,但如果它是数组中的最后一项,那么我希望它循环并返回第一项。
例如,如果传入的 ID 是,52027f4354c8a8fd33000008
那么我希望它返回 0 处的对象,即{"id" : "51fcd6fcf22d94c881000005","creator" : true}