ios9 Safari miscalculating sum

心已入冬 提交于 2019-12-13 13:06:20

问题


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

  1. why this is happening in ios9
  2. 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.


回答1:


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



来源:https://stackoverflow.com/questions/52857259/ios9-safari-miscalculating-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!