我正在使用Coffescript、underscore.js、knockout,并且我尝试按日期对数组进行排序,但由于某些原因,它不起作用
let accounts = [
{
id: 101,
content: "abc1",
createdDate: "2015-12-22T00:00:00"
},
{
id: 102,
content: "abc2",
createdDate: "2012-12-22T00:00:00"
}
]这就是我用coffeescript编写代码的方式
_.sortBy(accounts, (a) -> a.createdDate)在JS中生成的相同代码
return this.accounts(_.sortBy(accounts, function(a) {
return a.createdDate;
}));请告诉我哪里出错了。我没有收到任何错误,但是数组没有按日期排序。
发布于 2020-04-10 01:33:52
您的JSON语法无效,并且没有createdDate属性,应该如下所示:
accounts = [
{
id: 102,
content: "abc",
createdDate: "2015-12-22T00:00:00"
}
]因此,您可以在编写时使用函数(使用=>而不是->)。
工作示例:
let accounts = [
{
id: 101,
content: "abc1",
createdDate: "2015-12-22T00:00:00"
},
{
id: 102,
content: "abc2",
createdDate: "2012-12-22T00:00:00"
},
{
id: 103,
content: "abc3",
createdDate: "2018-12-22T00:00:00"
}
]
accounts = _.sortBy(accounts, (a) => a.createdDate)
console.log(accounts)<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
当然,id和content只是一个例子。
https://stackoverflow.com/questions/61126763
复制相似问题