我有一个排序倍的Array.sort()函数,但是,它使返回该错误。这里是我的代码:
sortTime(columnIndex, sortingAZ){
var rowArray = this.get('tableArr').slice(0); //gets array of arrays
rowArray.sort(function(a,b) {
var time1 = this.formatTime(a[columnIndex]); //formats time into military time
var time2 = this.formatTime(b[columnIndex]);
return time1 - time2;
});
这里是被称为formatTime功能:
formatTime(time){
//seperates time into hours and minutes
var colonIndex = time.search(":");
var hour = parseInt(time.substring(0, colonIndex));
var minute = time.substring(colonIndex+1, time.length);
if(time.search("pm")>=0&&hour!=12){ //if it is pm, add 12 to convert to military time (except 12 pm)
hour+=12;
}
else if(time.search("am")>=0&&hour==12){ //if it is 12 am, set hour to 0
hour = 0;
}
var milTime = hour.toString()+minute.toString(); //recombine hour and minute
milTime = parseInt(milTime);
return milTime;
}
我已经通过调用formatTime()
测试console.log(formatTime(rowArray[0][columnIndex]))
功能,并正确执行,没有错误。错误似乎是本地的rowArray.sort()
功能。
另外,我是比较新在这里,所以我们还是我知道如果你需要任何详细信息,如果有什么问题我的职务。
编辑:这是从How to access the correct `this` inside a callback?不同的,因为我的解决方案只需要一个箭头的功能。我很欣赏这虽然的深入解释
将其更改为箭头功能,使这种情况下将可里面。在常规的功能,您将无法访问,直到,除非你是指这一个局部变量或将其更改为箭头的功能如下图所示
rowArray.sort((a,b) => {
var time1 = this.formatTime(a[columnIndex]); //formats time into military time
var time2 = this.formatTime(b[columnIndex]);
return time1 - time2;
});
这是在不确定的compareFunction。尝试:
sortTime(columnIndex, sortingAZ){
var rowArray = this.get('tableArr').slice(0); //gets array of arrays
var that = this;
rowArray.sort(function(a,b) {
var time1 = that.formatTime(a[columnIndex]); //formats time into military time
var time2 = that.formatTime(b[columnIndex]);
return time1 - time2;
});