My code involves calculating the sum of key/value pairs in a hash within a loop. I have noticed that there is a discrepancy in how the sum is calculated on ios9 Safari compared to other platforms. While I can address this issue for this specific scenario, our extensive codebase utilizes similar syntax, prompting me to seek a deeper understanding of:
- why ios9 behaves differently
- if there is a universal solution that can be applied across all objects with a Vue
__ob__
object.
Feel free to test out the code here: . The code snippet is also provided below:
// Defining a hash
var totalItems, sum, type, value
totalItems = {}
totalItems['0'] = 3
// This inclusion of __ob__ is generated dynamically by Vue,
// but for illustrative purposes, it's manually included to highlight the ios9 bug
totalItems.__ob__ = new Object()
Object.defineProperty(totalItems, '__ob__', {
enumerable: false,
writable: true,
configurable: true
});
// Looping through the hash
sum = 0
for (type in totalItems) {
value = totalItems[type];
sum += value;
}
// In ios9 Safari, sum equals 6 -- it iterates over the '0' key twice
// In other browsers and newer iOS versions, sum equals 3!
UPDATE:
After conducting further research, it seems that this discrepancy is a known bug in Safari on ios9 devices. It affects hashes containing the key '0' as well as arrays. The issue appears to be specific to for-in
loops. Other methods like .forEach
and .reduce
function correctly. View the showcase here: . If liveweave loads slowly initially, try refreshing the page a couple of times. Unfortunately, jsfiddle and codepen do not work properly on ios9 at present. I have reported this problem to Apple.