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()而不需要回分配。
添加回答
举报