gpt4 book ai didi

javascript - 如何在 Javascript 中从数组中查找上一个或下一个元素?

转载 作者:行者123 更新时间:2023-12-03 00:22:32 24 4
gpt4 key购买 nike

I have one form where i am getting id.I am getting one array of ids from database. I have to check first that current_id is in array or not. for this I am writing below code that is working for me.

var arr = [{'id':4},{'id':5},{'id':7},{'id':8},{'id':9}];

var current_id = 5;
for(var i=0; i<arr.length; i++)
{
if (arr[i] == current_id)
return true;
}

现在假设我想转到current_id的上一个id或者我想转到current_id的下一个id如何在javascript中获取此类数据。

例如:

我的 current_id = 5。用户将点击 previous_button 然后它应该到达 {'id':4} 。如果用户点击 next_button 那么它应该转到 {'id':7}

如果用户已经在 current_id = 4 上并且他点击了 previous_button 它应该返回 false。 next_button 也是如此。

提前致谢。

最佳答案

您可以通过多种方法来做到这一点。

var arr = [{'id':4},{'id':5},{'id':7},{'id':8},{'id':9}], arrids=arr.map(e=>e.id);
var current_id = 5, prev_btn = $("#prev"), next_btn = $("#nex");
prev_btn.click(e=>{
current_id--;
var prevObj = arr[arrids.indexOf(current_id)] ? arr[arrids.indexOf(current_id)] : null;
console.log(prevObj);
});
next_btn.click(e=>{
current_id++;
var nextObj = arr[arrids.indexOf(current_id)] ? arr[arrids.indexOf(current_id)] : null;
console.log(nextObj);
})

根据您的需要更改此设置。

关于javascript - 如何在 Javascript 中从数组中查找上一个或下一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54248347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com