3 回答

TA貢獻1757條經驗 獲得超7個贊
您可以使用Array.prototype.filter從數組中刪除項目。您可以使用Array.prototype.join逗號字符等分隔符來組合數組元素:
itemSelectionChanged(e) {
// Use object destructure to get property `ID`
const { ID } = e.itemData;
if (e.itemData.selected) {
// Check if element is in array so a duplicate is not added
// Note: this only works with primitive values, not objects
if (this.users.indexOf(ID) < 0) {
this.users.push(ID);
}
// Join array items with comma character
console.log(this.users.join(","));
} else {
// Remove items using filter
this.users = this.users.filter(user => user !== ID);
}
}

TA貢獻1804條經驗 獲得超8個贊
除了filter(),您還可以使用splice()withindexOf()從數組中刪除項目。else在塊中包含以下內容
const index = this.users.indexOf(e.itemData.ID, 0);
if (index > -1) {
this.users.splice(index, 1);
}
我已經擴展了你的Stackblitz。
filter()和之間的區別splice()是 whilefilter()返回一個新數組,splice()就地修改數組。因此,如果您使用filter(),則需要將其分配回變量 like this.users = this.users.filter(...),splice()而不需要回分配。
添加回答
舉報