为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕少森 2022-05-22 11:08:10
我开发了一个自动完成下拉菜单。当我选择用户时,我将 ID 存储在 users 数组中。当我选择一个用户时,它被添加到数组中,但是当取消选择用户时,有没有办法将它从数组中删除?我怎样才能做到这一点?还有一种方法可以将数组转换为字符串,以便输出字符串,例如:“1,2”?.tsusers: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>
查看完整描述

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

    }

  }


查看完整回答
反对 回复 2022-05-22
?
UYOU

TA贡献1878条经验 获得超4个赞

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



查看完整回答
反对 回复 2022-05-22
?
胡说叔叔

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()而不需要回分配。


查看完整回答
反对 回复 2022-05-22
  • 3 回答
  • 0 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号