0

我需要在特定函数中使用各种数组,但我不禁认为我这样做的效率非常低:

function GetTimeLeft(){
var TimeUnformatted = document.querySelectorAll('[id="SomeIdName"]')[0].innerText.match(/\d{1,}d\s\d{1,}h/ig);
var i;
if (TimeUnformatted){
    var Daysunformatted = [];
    var Hoursunformatted = [];
    var DaysFormatted = [];
    var HoursFormatted = [];
    var DaysToSeconds = [];
    var HoursToSeconds = [];
    var TimeInSeconds = [];
    for (i=0;i<TimeUnformatted.length;i++){
        Daysunformatted[i]  = TimeUnformatted[i].match(/\d{1,}d/)[0];
        Hoursunformatted[i] = TimeUnformatted[i].match(/\d{1,}h/)[0];
        if (Daysunformatted[i])  DaysFormatted[i]  = Number(Daysunformatted[i].match(/\d{1,}/)[0]);
        if (Hoursunformatted[i]) HoursFormatted[i] = Number(Hoursunformatted[i].match(/\d{1,}/)[0]);

        if (DaysFormatted[i])  DaysToSeconds[i]  = DaysFormatted[i]*24*60*60;
        if (HoursFormatted[i]) HoursToSeconds[i] = HoursFormatted[i]*60*60;

        if (DaysToSeconds[i] && HoursToSeconds[i]) TimeInSeconds[i] = DaysToSeconds[i] + HoursToSeconds[i];
    }
    return TimeInSeconds;//an Array.
} else {
    return [0];
}

}

编辑:说清楚,因为我表达得很糟糕。我尝试“随时随地分配”,没有最初的 var 语句,但 javascript 大喊大叫并告诉我他没想到“[”:

function GetTimeLeft(){
var TimeUnformatted = document.querySelectorAll('[id="SomeIdName"]')[0].innerText.match(/\d{1,}d\s\d{1,}h/ig);
var i;
if (TimeUnformatted){
    for (i=0;i<TimeUnformatted.length;i++){
        var Daysunformatted[i]  = TimeUnformatted[i].match(/\d{1,}d/)[0];
        var Hoursunformatted[i] = TimeUnformatted[i].match(/\d{1,}h/)[0];
        if (Daysunformatted[i])  var DaysFormatted[i]  = Number(Daysunformatted[i].match(/\d{1,}/)[0]);
        if (Hoursunformatted[i]) var HoursFormatted[i] = Number(Hoursunformatted[i].match(/\d{1,}/)[0]);

        if (DaysFormatted[i])  var DaysToSeconds[i]  = DaysFormatted[i]*24*60*60;
        if (HoursFormatted[i]) var HoursToSeconds[i] = HoursFormatted[i]*60*60;

        if (DaysToSeconds[i] && HoursToSeconds[i]) var TimeInSeconds[i] = DaysToSeconds[i] + HoursToSeconds[i];
    }
    return TimeInSeconds;//an Array.
} else {
    return [0];
}

我知道我可以做多项任务,但仍然没有更好的方法来做我想做的事吗?

4

1 回答 1

1

那行代码的问题是var。删除var它,它就像你上面的代码一样工作。

Daysunformatted[i]  = TimeUnformatted[i].match(/\d{1,}d/)[0];

我能看到改进代码的唯一方法是将 reg exp 移到 for 循环之外。

var reDays = /\d{1,}d/;
var reHours = /\d{1,}h/;
for (i=0;i<TimeUnformatted.length;i++){
        Daysunformatted[i]  = TimeUnformatted[i].match(reDays)[0];
        Hoursunformatted[i] = TimeUnformatted[i].match(reHours)[0];

并且您可以使用捕获组来获取小时数,因此您不必进行第二次降低 d/h 的匹配。

var reDays = /(\d{1,})d/;
var TimeUnformatted = "10d 1h";
 Daysunformatted[i]  = (TimeUnformatted[i].match(reDays) || [,])[1];
于 2013-03-21T13:17:46.303 回答