0

我正在尝试构建一个 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>
4

1 回答 1

0

几件小事

考虑在您的 var 部分中声明 time 和 isoTime up ,否则它们只会神奇地出现并且没有定义范围。

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(...
于 2012-07-29T03:11:32.660 回答