亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從數組中刪除未選擇的項目

從數組中刪除未選擇的項目

慕少森 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 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號