3 回答

TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個(gè)贊
是什么a.index?你的意思是數(shù)組索引?
我想你只是想在數(shù)組中找到項(xiàng)目的索引,然后在下一個(gè)索引處取對(duì)象:
nextOrder() {
const index = this.orders.findIndex(order => order.order_id === 234)
if (index === -1 || index === this.orders.length - 1) {
// No such order or no next order
return null
}
return this.orders[index + 1]
}
上一個(gè)訂單在 index 處index - 1,下一個(gè)訂單在 index 處index + 1。要檢查任一順序是否存在,您只需要檢查索引是否在數(shù)組的范圍內(nèi)。i只要 ,索引就在數(shù)組的范圍內(nèi)0 <= i <= (orders.length - 1)。
如果index - 1 >= 0(不能為負(fù)索引)且index - 1 <= array.length - 1(不能大于數(shù)組的最后一個(gè)索引),則存在前一個(gè)順序。

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊
試試下面的代碼,
let id = 234; // your id let index = this.orders.findIndex(order => order.some_id === id); console.log(this.orders[index + 1]); // give you the next object

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
你可以簡單地使用findIndex
let arr = [{order_id: 234, text: 'foo'},{ order_id: 567, text: 'bar'}]
let findNextOrder = (id) => {
let index = arr.findIndex(({ order_id }) => order_id === id)
return index > -1 && index < arr.length - 1 ? arr[index + 1] : undefined
}
console.log(findNextOrder(234))
您不需要根據(jù)您對(duì)問題的評(píng)論進(jìn)行排序,您的對(duì)象上也沒有名為 index 的屬性。
添加回答
舉報(bào)