问题描述
我遇到了一个非常非常奇怪的JS问题,只能在iOS 6上的Mobile Safari浏览器上进行复制。
问题在于将一个给定值格式化为价格的函数,通过将数字拆除为2位小数,并在数字前面添加货币。这是功能。我稍后将解释如何重现该错误。
I ran into a very very very strange JS issue that is reproducing only on Mobile Safari browser on iOS 6.The issue is in a function that formats a given value to a price, by stripping down the number to 2 decimals and adds the currency in front of the number. Here are the functions. I will explain later on how to reproduce the bug.
formatCurrency = function(value, currency, fixedPrecision, colourize, blankIfZero) {
var text;
if (blankIfZero && (Math.abs(value) < 0.01 || value === undefined)) {
return "";
}
if (fixedPrecision) {
text = currency + Math.abs(value).toFixed(2);
} else {
text = currency + roundTo2Decimals(Math.abs(value));
}
if (value < 0) {
text = "-" + text;
}
if (colourize) {
var colorClass = (value < 0 ? "negative" : "positive");
text = "<span class='" + colorClass + "'>" + text + "</span>";
}
return text;
};
roundTo2Decimals = function(value) {
var sign = value < 0 ? -1 : 1;
return Math.round(Math.abs(value) * 100.0)/100.0 * sign;
};
如果我一遍又一遍地运行formatCurrency函数(例如在setInterval中)值(让我们说值= 1;以及货币=英镑)你会注意到每次800-1000次迭代,函数返回的值包含一个负数:GBP-1而不是GBP1。这个问题非常烦人我在JS函数中没有发现任何问题。
If I run the the formatCurrency function over and over again (within a setInterval for example) with the same value (lets say value=1; and currency="GBP") you will notice the once every 800-1000 iterations the value return by the function contains a negative amount: GBP-1 instead of GBP1. This issue is very annoying i I did not found any issue within the JS functions.
我设法解决这个问题...但我很好奇这是什么问题有了这个实现。
I manage to fix the issue ... but I'm curious what is the issue with this implementation.
我错过了什么?
推荐答案
我想;
text = - + String(text);
text = "-" + String(text);
是问题。
我也常常在Safari中浏览iOS6相关的bug。如果我们希望它能够顺利执行,那JS似乎应该更加清洁!
Me too have been surfing around a lot for iOS6 related bugs in Safari. It seems the JS should be lot more cleaner if we want it to execute smooth!
这篇关于移动Safari iOS 6上的奇怪JavaScript行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!