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
- 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.
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!
UPDATE:
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.
Usually using for ... in is not a good idea. I believe your issue is related to that.
You can use for ... of ** or do a regular **for loop.
See a detailed explanation of what happens with for ... in here