ios9 Safari错误计算总和 [英] ios9 Safari miscalculating sum
问题描述
我有一些代码可以计算循环中哈希中键/值的总和。它似乎是在ios9 Safari上以不同的方式计算总和,与其他任何地方相比。虽然我可以找到一种方法来修复这个单独的用例,但是我们在整个大型代码库中都使用了这种类型的语法,所以我正在寻找一些理解
I have some code that calculates the sum of key/values in a hash in a loop. It appears to be calculating the sum in a different manner on ios9 Safari compared with anywhere else. Although I can find a way to fix this individual use case, we use this type of syntax throughout our large code base, so I am looking for some understanding of
- 为什么在ios9中发生这种情况
- 如果有办法全局修复它,那将适用于可能有Vue
__ ob__的所有对象
对象就可以了。
- why this is happening in ios9
- if there is a way to globally fix it that would be applicable to all objects that might have a Vue
__ob__
object on them.
在此尝试代码: https://liveweave.com/kKo88G 。我还粘贴在下面:
Try the code out here: https://liveweave.com/kKo88G. I also pasted it below:
// Define a hash
var totalItems, sum, type, value
totalItems = {}
totalItems['0'] = 3
// This definition of __ob__ is done dynamically by Vue,
// but I include it here by way of example of what breaks in ios9
totalItems.__ob__ = new Object()
Object.defineProperty(totalItems, '__ob__', {
enumerable: false,
writable: true,
configurable: true
});
// Loop through the hash
sum = 0
for (type in totalItems) {
value = totalItems[type];
sum += value;
}
// sum is 6 in ios9 Safari -- it loops through the '0' key twice
// sum is 3 in all other browsers and newer ios versions!
更新:
在进一步调查之后,这似乎是ios9设备上的Safari中的一个错误。它既适用于带有键'0'的哈希值,也适用于数组。这似乎只是 for-in
循环的问题。 .forEach
, .reduce
等工作正常。 https://liveweave.com/znUFU2 展示了这一点。如果liveweave首先加载缓慢,则刷新页面几次。 js fiddle / codepen / etc.目前不适用于ios9。我已向Apple报告此事。
After investigating further, this appears to be a bug in Safari on ios9 devices. It applies both to hashes with the key '0' in them and to arrays. It only seems to be an issue with for-in
loops. .forEach
, .reduce
, etc. work fine. https://liveweave.com/znUFU2 showcases this. Refresh the page a couple of times if liveweave is slow to load at first. js fiddle/codepen/etc. don't work on ios9 at the moment. I have reported this to Apple.
推荐答案
通常使用 for ... in 并不是一件好事理念。我相信你的问题与此有关。
Usually using for ... in is not a good idea. I believe your issue is related to that.
您可以使用表示**或**进行常规** 循环。
See a detailed explanation of what happens with for ... in here
这篇关于ios9 Safari错误计算总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!