【问题标题】:ios9 Safari miscalculating sumios9 Safari 计算错误总和
【发布时间】:2019-03-22 06:33:49
【问题描述】:

我有一些代码可以在循环中计算散列中的键/值之和。与其他任何地方相比,它似乎在 ios9 Safari 上以不同的方式计算总和。虽然我可以找到一种方法来修复这个单独的用例,但我们在整个大型代码库中都使用这种类型的语法,所以我正在寻找一些理解

  1. 为什么在 ios9 中会发生这种情况
  2. 如果有一种方法可以全局修复它,它将适用于所有可能具有 Vue __ob__ 对象的对象。

在此处试用代码:https://liveweave.com/kKo88G。我也贴在下面:

// 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小提琴/codepen/等。暂时不要在ios9上工作。我已将此情况报告给 Apple。

【问题讨论】:

标签: javascript vue.js ios9 ecmascript-5


【解决方案1】:

通常使用 for ... in 不是一个好主意。我相信你的问题与此有关。

您可以使用 for ... of ** 或执行常规的 **for 循环。

here 中查看 for ... 的详细说明

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多