在JavaScript数组中获取Next和Previous元素

时间:2009-06-29 13:09:41

标签: javascript arrays

我有一个大型数组,带有非顺序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 个答案:

答案 0 :(得分:5)

为什么不添加属性'Prev'&amp;那个阵列'下一步'?

PhotoList[89725] = new Array();
PhotoList[89725]['Prev'] = 89724;
PhotoList[89725]['Next'] = 89726;
PhotoList[89725]['ImageID'] = '89725';
PhotoList[89725]['ImageSize'] = '123';

这只是'双链表'数据结构。

答案 1 :(得分:5)

根据您的示例,ID是顺序的...... 这是编写示例的另一种方式。新的Array()确实不是你应该使用的,因为那些是你正在创建的对象。另外,我把数字留作字符串,但我不确定你为什么要那样做。你可以添加下一个和prev如kuy建议

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

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

答案 2 :(得分:3)

除了在您的数组中找到一个条目之前,按顺序遍历可能的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);

答案 3 :(得分:1)

我同意其他引用你应该使用的对象不是数组。还要确保使用文字表示法创建新数组,而不是使用内置类型创建新关键字。新关键字是坏消息,您可以破坏全局对象。查看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;
});

答案 4 :(得分: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;

答案 5 :(得分: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")
}

答案 6 :(得分:-1)

您可以使用grep函数并计算指定数组的上一个或下一个项目:

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

答案 7 :(得分:-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;
?>