我有将时间间隔(总和和平均值)转换为“ hh:mm:ss”格式的代码,除在IE 11中出现此错误外,其他任何地方都很好:
SCRIPT438:对象不支持属性或方法'padStart'
我该如何重写此代码以使其起作用?
var times = [3600000, 60000, 1000];
function formatTime(avg) {
return times.map(function (t) {
var value = Math.floor(avg / t);
avg %= t;
return value;
}).map(function (v) {
return v.toString().padStart(2, 0);
}).join(':');
}
console.log(formatTime(32939000)); // 09:08:59
在最后一个
padStart(2, 0)
语句中调用 return
。如何在IE11中使用它?
答案 0 :(得分:3)
根据padStart
的MDN文档,Internet Explorer不支持该功能。但是,他们还提供了polyfill,如果缺少padStart
,则会添加padStart
。只需将代码块添加到程序的开头,任何浏览器中就会出现// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
if (!String.prototype.padStart) {
String.prototype.padStart = function padStart(targetLength, padString) {
targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0;
padString = String(typeof padString !== 'undefined' ? padString : ' ');
if (this.length >= targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + String(this);
}
};
}
。
DocMgrTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 120
HealthCheckPath: /dms/
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 60
HealthyThresholdCount: 2
Name: !Sub eds-${Environment}-docmgr-tg
Port: 80
Protocol: HTTP
TargetType: instance
UnhealthyThresholdCount: 8
Matcher:
HttpCode: 200-499
VpcId:
Fn::ImportValue: !Sub 'eds-${Environment}-ecs-cluster-vpc'
# Create a rule on the load balancer for routing traffic to the target group
LoadBalancerRule:
Type: AWS::ElasticLoadBalancingV2::ListenerRule
Properties:
Actions:
- TargetGroupArn: !Ref 'DocMgrTargetGroup'
Type: 'forward'
Conditions:
- Field: path-pattern
Values:
- "/dms*"
ListenerArn:
Fn::ImportValue: !Sub 'eds-${Environment}-ecs-cluster-listener'
Priority: !Ref 'Priority
(根据MDN's about page,先前的代码位于公共领域。)
答案 1 :(得分:1)
对于特定于 的情况-在处理具有1位或2位数字的时间部分(小时,分钟,秒)时,可以替换:
return v.toString().padStart(2, 0);
具有:
return ("0" + v).slice(-2);
var times = [3600000, 60000, 1000];
function formatTime(avg) {
return times.map(function (t) {
var value = Math.floor(avg / t);
avg %= t;
return value;
}).map(function (v) {
return ("0" + v).slice(-2);
}).join(':');
}
console.log(formatTime(32939000)); // 09:08:59