javascript date.js解析并排序对象数组

时间:2012-07-29 02:37:45

标签: javascript json parsing date datejs

我正在尝试构建一个javascript对象数组,使用date.js解析日期,然后使用date.js比较方法对对象进行排序。以下是我为了证明我的两个问题而编写的一些代码。

问题1:如何忽略date.js无法解析的日期并发出警告? 问题2:如何按这些日期对对象数组进行排序? (有或没有date.js)

我的直觉告诉我,我这样做是错的,并且有更好的方法。想法?

    <script type="text/javascript" src="depend/date.js"></script>

<script type="text/javascript">
var timedata = ["tomorrow", "today", "next thursday", "2012-08-02T04:00:00.000Z"]; // test data
var myArrayOfObjects = [];

//Iterate through the timedata array
for(var row = 0; row < timedata.length; row++){     
    var cleanrow = true;

    // Here is the first problem, on the 2012-08-02T04:00:00.000Z string can't be parsed (Date.parse(timestr) returns 0) 
    // even though it was previously created with .toISOString method below as a test
    // Error: Ignoring row 3, could not parse this date: 2012-08-02T04:00:00.000Z
    if (Date.parse(timedata[row])){ 
        time =  Date.parse(timedata[row]);
        isoTime = time.toISOString();
    }else{
        console.log("Ignoring row " + row + ", could not parse this date: " + timedata[row]);
        cleanrow = false;
    }
    var xdata = "dummytestdata";
    var weight = "dummytestdata";
    if(cleanrow) {
        myArrayOfObjects.push({x: xdata, xytime: isoTime, weight: weight});
    }
}

// Here is the second problem.  
// Error: TypeError: Date.parse(a.xytime) is null
myArrayOfObjects = myArrayOfObjects.sort(function(a,b){ return Date.parse(a.xytime).compareTo(Date.parse(b.xytime)); });

// Show that the objects are sorted by dates
for(var row = 0; row < myArrayOfObjects.length; row++) {
    console.log(myArrayOfObjects[row].xytime);
}
</script>

1 个答案:

答案 0 :(得分:0)

一些小事

考虑在var部分中声明时间和isoTime,否则它们只是神奇地出现并且没有定义范围。

var cleanrow = true, isoTime = null, time = null;

考虑仅解析timedata[row]一次,并重用该变量。它可能会稍微清理一下代码。

time = Date.parse(timedata[row])
if (time){ 
    isoTime = time.toISOString();

是否有任何理由需要将isoTime作为字符串,而不是仅仅将日期存储在您放入数组中的对象上?让我觉得您也可以存储日期,并在排序

中使用它
myArrayOfObjects.push({x: xdata, xytime: isoTime, weight: weight, realTime: time});
//...
myArrayOfObjects = myArrayOfObjects.sort(function(a,b){ return a.realTime.compareTo(b.realTime); });

另外,查看mozilla doco,sort方法对数组起作用,而不是返回一个新数组。

myArrayOfObjects = myArrayOfObjects.sort(...
//should be just
myArrayOfObjects.sort(...