我需要在特定函数中使用各种数组,但我不禁认为我这样做的效率非常低:
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];
}
我知道我可以做多项任务,但仍然没有更好的方法来做我想做的事吗?