繁体   English   中英

PolymerJS:如何正确使用set()和forEach循环更新数组中的所有项目

[英]PolymerJS: How to Update all Items in an Array with set() and a forEach loop properly

我有一个看起来像这样的数组:

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

我想将每个 item 设置true 为此,我有一个按钮,可以在点击时触发一个事件,该事件将执行以下代码段。

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);
});

具体在哪里,我用的是部分dots与连接i看来哈克给我。


与Vue相同的代码

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

Polymer API指出:

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


题:

因为我使用索引的部分由于缺少更好的用语而显得有些笨拙 ,所以我想知道, 是否存在一种更方便的方法来使用Polymer中的forEach循环来更新数组中的所有项目。

谢谢。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM