从数组中删除未选择的项目

我开发了一个自动完成下拉菜单。

当我选择用户时,我将 ID 存储在 users 数组中。

当我选择一个用户时,它被添加到数组中,但是当取消选择用户时,有没有办法将它从数组中删除?我怎样才能做到这一点?

还有一种方法可以将数组转换为字符串,以便输出字符串,例如:“1,2”?

.ts


users:any [] =[];

 itemSelectionChanged(e){

   console.log("item",e)

   if(e.itemData.selected == true){

     this.users.push(e.itemData.ID);

     console.log(this.users)


     //output as a string and not an array.... like "1,2"

   }

   else{

     //Remove the unselected value in the array this.users e.itemData.ID

   }

 }

.html


<dx-drop-down-box [(value)]="treeBoxValue" valueExpr="ID" displayExpr="name" placeholder="Select a value..."

    [showClearButton]="true" [dataSource]="treeDataSource" (onValueChanged)="syncTreeViewSelection()">

    <div *dxTemplate="let data of 'content'">

        <dx-tree-view [dataSource]="treeDataSource" dataStructure="plain" selectionMode="multiple"

            showCheckBoxesMode="normal" [selectNodesRecursive]="false" displayExpr="name" [searchEnabled]="true"

            [selectByClick]="true" (onItemSelectionChanged)="itemSelectionChanged($event)">

        </dx-tree-view>

    </div>

</dx-drop-down-box>

http://img3.mukewang.com/6289a92f00018d1505840299.jpg

慕少森
浏览 139回答 3
3回答

长风秋雁

您可以使用Array.prototype.filter从数组中删除项目。您可以使用Array.prototype.join逗号字符等分隔符来组合数组元素:&nbsp; itemSelectionChanged(e) {&nbsp; &nbsp; // Use object destructure to get property `ID`&nbsp; &nbsp; const { ID } = e.itemData;&nbsp; &nbsp; if (e.itemData.selected) {&nbsp; &nbsp; &nbsp; // Check if element is in array so a duplicate is not added&nbsp; &nbsp; &nbsp; // Note: this only works with primitive values, not objects&nbsp; &nbsp; &nbsp; if (this.users.indexOf(ID) < 0) {&nbsp; &nbsp; &nbsp; &nbsp; this.users.push(ID);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; // Join array items with comma character&nbsp; &nbsp; &nbsp; console.log(this.users.join(","));&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; // Remove items using filter&nbsp; &nbsp; &nbsp; this.users = this.users.filter(user => user !== ID);&nbsp; &nbsp; }&nbsp; }

UYOU

试试下面的代码,复制到else语句中this.users=this.users.filter(x=>x!=e.itemData.ID);

胡说叔叔

除了filter(),您还可以使用splice()withindexOf()从数组中删除项目。else在块中包含以下内容const index = this.users.indexOf(e.itemData.ID, 0);if (index > -1) {&nbsp; this.users.splice(index, 1);}我已经扩展了你的Stackblitz。filter()和之间的区别splice()是 whilefilter()返回一个新数组,splice()就地修改数组。因此,如果您使用filter(),则需要将其分配回变量 like this.users = this.users.filter(...),splice()而不需要回分配。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript