预期的 ';' I.E 中的异常 (JavaScript, jQuery)

Expected ';' exception in I.E (JavaScript, jQuery)

我正在测试我的网站的 I.E 兼容性,我马上 运行 遇到了很多问题:

DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
webshop.html
HTML1300: Navigation occurred.
webshop.html
SCRIPT1004: Expected ';'
main.js (16,18)

此时我最关心的是 ;不符合预期,因为每次我检查我的代码时它就在那里。

IE doesn't support for..of, so you can either transpile your code (e.g. with Babel) or use a good old forEach:

this.cartShop.forEach(function(item) {
    if (...) { ... }
}, this);

Update:我现在看到在 if 块内有一个 return 语句可以提前退出函数,那就是为什么我建议的代码表现不同。我不推荐这种方法,因为它会导致意外行为和代码重复。通常,使用 break.

跳出循环

我看到你首先在检查商品是否在购物车中:你可以使用 find:

var item = this.cartShop.find(function(item) {
    return item.name === name && ...
});

if (item) {
    item.quantity += quantity;
} else {
    item = new this.Item(...);
    this.cartShop.push(item);
}

this.saveLocalCart();

不幸的是,find 再次 在 IE 中不可用 ,但与 for..of 相反,您可以简单地提供一个 polyfill。或者,您始终可以将旧代码与经典 for 循环一起使用:

for (var i = 0; i < this.cartShop.length; i++) {
    var item = this.cartShop[i];
    if (...) { ... }
}

更冗长,可读性更差,但仍然有效。