[英]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的map
, every
, some
和filter
方法也是如此。
this.items.forEach(function(item, index) {
this.set('items.'+index+'.completed', true);
}.bind(this));
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.