【问题标题】:PolymerJS: How to Update all Items in an Array with set() and a forEach loop properlyPolymerJS:如何使用 set() 和 forEach 循环正确更新数组中的所有项目
【发布时间】:2015-11-16 02:07:09
【问题描述】:

我有一个如下所示的数组:

items: [
    {title: 'First Title', completed: false}, 
    {title: 'Second Title', completed: false}, 
    {title: 'Third Title', completed: false}
];

我想将每个 item 设置为 true。为此,我有一个按钮,可以触发执行以下代码 sn-ps 的点击事件。

Polymer 团队使用 for 循环设置布尔值:

for (var i = 0; i < this.items.length; ++i) {
    this.set(['items', i, 'completed'], true);
}

我个人更喜欢使用 forEach 循环,因为我想将 Polymer 与不同的框架进行比较,碰巧我在类似情况下使用了 forEach 循环。

我的工作解决方案:

var that = this;
this.items.forEach(function(item) {
    var i = that.items.indexOf(item);

    that.set('items.' + i + '.completed', true);
    // or
    // that.set(['items', i, 'completed'], true);
});

特别是我使用dotsi 连接的部分对我来说似乎很老套。


与 Vue 相同的代码

this.items.forEach(function(item) {
    return item.completed = true;                   
});

Polymer API 声明:

set(path, value, root) path (string|Array) 要读取的值的路径。路径可以指定为字符串(例如 foo.bar.baz)或路径部分的数组(例如 ['foo.bar', 'baz'])。请注意,不支持括号中的表达式;基于字符串的路径部分必须用点分隔。请注意,当取消引用数组索引时,索引可以直接用作虚线部分(例如 users.12.name 或 ['users', 12, 'name'])。 价值 * 在指定路径设置的值。 根对象= 计算路径的根对象。


问题:

因为我使用索引的部分似乎有点hacky,因为缺少更好的术语,我想知道,是否有更方便的方法来使用 forEach 循环Polymer 更新数组中的所有项目。

谢谢。

【问题讨论】:

    标签: javascript foreach polymer


    【解决方案1】:

    forEach 的回调函数可以有一个引用当前索引的第二个参数。这也适用于 Array 的 mapeverysomefilter 方法。

    ES5 版本

    this.items.forEach(function(item, index) {
      this.set('items.'+index+'.completed', true);
    }.bind(this));
    

    ES6 版本

    this.items.forEach((item, index) => this.set(`items.${index}.completed`, true));
    

    来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Parameters

    【讨论】:

    • 我认为这实际上是一个更令人困惑的 sn-p。我猜你的回答暗示,没有更方便的方法可以将 Polymer 中的所有数组项 settrue
    猜你喜欢
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多