【发布时间】:2017-06-08 17:02:49
【问题描述】:
我正在使用 string.endswith() 循环遍历 JSON 对象并找出对象 endswith 的任何属性是否为 "Value" 子字符串。
在查明对象属性是否以"Value" 结尾后,我试图将属性的值四舍五入为 2 位小数,默认为 5 位小数。
这是我的代码
var MyObj= [{"$id":"1","GeoName":"EAST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206},{"$id":"2","GeoName":"WEST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206}];
Obj = JSON.parse(JSON.stringify(MyObj)).map(function (e) {
return Object.keys(e).reduce(function (p, n) {
if (n.endsWith("Value"))
p[n] = Math.round(e[n] * 100) / 100;
else
p[n] = e[n];
return p;
}, {})
});
以上代码在chrome 和Firefox 中运行良好,而IE 抛出endsWith 不是函数异常。
我发现使用了 pollyfills 的此类问题,我尝试过但失败了。我什至不确定我是否正确使用了 pollyfill。
这就是我的做法,
function polyFillEndswith(searchString, position) {
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
}
}
Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
return Object.keys(e).reduce(function (p, n) {
if (n.polyFillEndswith("Value", "0"))
p[n] = Math.round(e[n] * 100) / 100;
else
p[n] = e[n];
return p;
}, {})
});
上面的代码是否正确?如果不是,我该如何改变它以实现我的目标?
【问题讨论】:
-
他们说他们试过了,但是没有用。我认为他们的意思是他们尝试了他们共享的代码。 @MichałPerłakowski
标签: javascript jquery json asp.net-mvc polyfills