let journal = [..............];
//need sort by key time
function sortByStatus(){
return journal.sort(function(a, b) {
return a.fly_status - b.fly_status;
});
}
function sortByTime(){
return journal.sort(function(a, b) {
console.log( new Date( a.start_datetime).getTime() );
return new Date( a.start_datetime).getTime()
- new Date( b.start_datetime).getTime();
});
}
我怎样才能做到这个逻辑:
journal.sortByStatus().sortByTime()
.....数组的其他一些方法?
我可以仅在日志数组中添加这些方法,而不是在我的页面中添加所有数组吗?
最佳答案
一种方法是定义您自己的对象。此示例不允许链接方法,但您可以按顺序调用它们:
let Journal = function(list){
this.list = list || [];
this.sortByStatus = function(){
return this.list.sort(function(a, b) {
return a.fly_status - b.fly_status;
});
}
this.sortByTime = function(){
return this.list.sort(function(a, b) {
return new Date( a.start_datetime).getTime() - new Date( b.start_datetime).getTime();
});
}
}
let journal = new Journal([
{fly_status:50, start_datetime: 5},
{fly_status:5, start_datetime: 50}
]);
console.log(journal.sortByStatus());
console.log(journal.sortByTime());
为了允许链接,请在方法完成后返回对象本身(尽管使用排序,您可能只选择一种排序):
let Journal = function(list){
this.list = list || [];
this.sortByStatus = function(){
list.sort(function(a, b) {
return a.fly_status - b.fly_status;
});
return this;
}
this.sortByTime = function(){
list.sort(function(a, b) {
return new Date( a.start_datetime).getTime() - new Date( b.start_datetime).getTime();
});
return this;
}
}
let journal = new Journal([
{fly_status:50, start_datetime: 5},
{fly_status:5, start_datetime: 50}
]);
console.log(journal.sortByStatus().sortByTime().list);
关于javascript - 为数组原型(prototype)添加了新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43030075/