我正在使用 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;
}));
请让我知道我哪里出错了。我没有收到任何错误,但数组没有按日期排序。
最佳答案
您的 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
只是一个例子。
关于javascript - underscore.js 中按日期对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61126763/