在JavaScript数组中获取下一个和上一个元素

4

我有一个大数组,其中包含非连续的ID,看起来像这样:

PhotoList[89725] = new Array();
PhotoList[89725]['ImageID'] = '89725';
PhotoList[89725]['ImageSize'] = '123';
PhotoList[89726] = new Array();
PhotoList[89726]['ImageID'] = '89726';
PhotoList[89726]['ImageSize'] = '234';
PhotoList[89727] = new Array();
PhotoList[89727]['ImageID'] = '89727';
PhotoList[89727]['ImageSize'] = '345';
Etc....

我正在尝试找出如何根据ID获取下一个和上一个ID... 这样我就可以做这样的事情:

<div id="current">Showing You ID: 89726 Size: 234</div>
Get Prev Get Next

显然,如果我们在数组的末尾或开头,我们只需发送一条消息...
8个回答

6
为什么不在该数组中添加“上一页”和“下一页”的属性?
PhotoList[89725] = new Array();
PhotoList[89725]['Prev'] = 89724;
PhotoList[89725]['Next'] = 89726;
PhotoList[89725]['ImageID'] = '89725';
PhotoList[89725]['ImageSize'] = '123';

这只是一个“双向链表”数据结构。


5

根据您的示例,这些ID是连续的... 这是另一种编写您示例的方式。new Array()真的不是您应该使用的,因为您正在创建对象。此外,我将数字保留为字符串,但我不确定您为什么要这样做。您可以像kuy建议的那样添加next和prev。

PhotoList[89725] = {ImageID: '89725',
                    ImageSize: '123'};
PhotoList[89725] = {ImageID: '89726',
                    ImageSize: '234',
                    Next: '89727',
                    Prev: '89725'};
PhotoList[89725] = {ImageID: '89727',
                    ImageSize: '345'};

所有这些都可以像其他结构一样访问。

1
我同意Jerry的看法。忘掉数组吧,PhotoList也应该是一个对象。var PhotoList = { 89725: { ImageID: 89725, ImageSize: 123, next: 89726}, 89725: {} 等等... - Prestaul

3

除了按顺序迭代可能的id,直到找到在数组中有条目的id之外,没有其他方法。例如:

function findClosest(arr, id, increasing) {
    var step = increasing ? 1 : -1;
    for(var i=id+step; i>=0 && i<=max_id; i+=step)
        if( arr[id] )
            return id;
}

显然,这种方法需要跟踪max_id,以便您不会无限迭代;在这里,我假设它是一个全局变量,但您可能希望将其作为findClosest函数的参数。您可以像这样调用此函数:

var prev = findClosest(arr, id, false);
var next = findClosest(arr, id, true);

1

我同意其他引用的观点,你应该使用对象而不是数组。另外,请确保使用文字表示法创建新数组,而不是使用内置类型的 new 关键字。new 关键字可能会对全局对象造成破坏。请查看 JSLint。

var a = new Array(); //bad dont use
var a = []; //this is the best way to create a new array
var o = {}; //create new objects like this

关于手头的问题。为什么不编写一个具有自己内部计数器的简单容器呢?
function PhotoListContainer(PhotoList)
{
    if(PhotoList === undefined)
        throw("no photo list");

    this.counter = 0;
    var self = this;

    this.current = function(){
         return PhotoList[self.counter];
    };

    this.next = function(){
        return PhotoList[self.counter + 1];
    };

    this.prev = function(){
        return PhotoList[self.counter - 1];
    };

    // You could even write a function that loops each value from the current counter :)
    this.each_from_counter = function(callback){
        for(var i = self.counter; i < PhotoList.length; i++)
        {
             callback(PhotoList[i], i);
             self.counter++;
        }        
    };

}

//use 

var pc = new PhotoListContainer(PhotoList);
pc.counter = 500;
pc.next(); //returns the 501st object
pc.prev(); //returns the 499th object
pc.each_from_counter(function(photo, index){
     photo.somehting;
});

0

根本不使用数组更好。

images = {
    0: {
        size: 12345, /* dont realy need as you can use JS to mesure the size. */
        title: "day 1 on holiday"
    },
    1: {
        size: 13549, /* dont realy need as you can use JS to mesure the size. */
        title: "day 2 on holiday"
    },
    2: {
        size: 16548, /* dont realy need as you can use JS to mesure the size. */
        title: "day 3 on holiday"
    },
}

for(x in images){
    /* x = "the id of the image." */
    url[] = "/images/" + x + ".png";
    title[] = images[x].title;
    size[] = images[x].size;
    console.log("File: " + url[x] + " , Title: " + title[x] + " , Size: " + size + "bytes")
}

尽管如此,这并没有帮助回答问题;OP已经指定他们想要计算给定已知键的前一个和后一个ID是什么,而其他键不一定是连续的。 - Sam Sehnert
这里的思路是什么?您使用从零开始的数字对对象进行索引。这比使用数组更好在哪里? - Stewart

0
var sibNum = 0;
var sibList = [];
var prevSiblingID = false;
for (n in w) {
   sibNum++;
   sibList[n] = {
      title : n,
      prevSiblingID : prevSiblingID
   };
       if (prevSiblingID) {
          sibList[prevSiblingID].nextSiblingID = n;
   }
   prevSiblingID = n;
};
sibList[prevSiblingID].nextSiblingID = false;

-1

你可以使用grep函数并计算指定数组的前一个或后一个项目:

object = $.grep(data, function(e) {
            if(e.id == yourId) {
                return data[data.indexOf(e) + 1]; // or -1 for prev item
            }
     });

-3

我认为你的图像列表将来自数据库,因此你可以尝试这段代码,这段代码对我有效。

<?
    $prev="";
    $next="";
    $cur=0;
    $i=0;
    $pid=$_GET['pid'];
    while($rowcon=mysql_fetch_assoc($result))
    {       
        $arr[$i]=$rowcon['pid'];
        if($rowcon['pid']==$pid)
        {
            $cur=$i;
        }
        $i++;
    }   
    if($cur<$num_rows)
        $next=$arr[$cur+1];
    else
        $next="";
    if($cur>0)
        $prev=$arr[$cur-1];
    else
        $prev="";
    echo $prev."   ".$cur."   ".$next;
?>

1
问题是关于 JavaScript 而不是 PHP。 - Hossam Aldeen Ahmed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接