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

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

打字稿 - 無法拼接數組

打字稿 - 無法拼接數組

收到一只叮咚 2021-11-12 14:55:14
我試圖在未選中復選框時刪除數組的一部分(如果復選框值與數組項中的值匹配)。當用戶單擊復選框時創建的數組工作正常,但是當未選中復選框時,我嘗試刪除/拼接的數組對象現在是字符串對象,因此無法拼接。我的困惑是關于為什么數組在第二次循環后“變成”字符串對象。我正在努力的主要代碼塊開始于:onCheckboxChange(option, event)Stackblitz 在這里:https ://stackblitz.com/edit/angular-match-groceries-sweetsimport { Component } from '@angular/core';// import * as d3 from "d3";@Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ]})export class AppComponent  {  name = 'Angular';  grocery_list: any;  treats: [];  box: any;  allTreats: any;  noDupes: any;  selectedAll: any;  isChecked: boolean;  showTreats: any;  checkedList: string[] = [];constructor(){}ngOnInit(){  this.getTreats();}  getTreats(){  this.grocery_list = [      {"fruit": "apple", "veggie": "lettuce", "sweets": ["cookies", "cake"]},      {"fruit": "orange", "veggie": "asparagus", "sweets": ["cookies", "ice cream"]},      {"fruit": "apple", "veggie": "carrots", "sweets": ["No Data", "cake"]},      {"fruit": "apple", "veggie": "lettuce", "sweets": ["cookies", "No Data"]},    ];  this.treats = this.grocery_list.map(x => x.sweets);   this.box = [].concat.apply([],this.treats);  this.noDupes = Array.from(new Set(this.box));  this.allTreats = Array.from(this.box)  }// this is where the check/uncheck logic starts    onCheckboxChange(option, event) {      let eChecked = event.target.checked;     if(eChecked) {       this.grocery_list.forEach(x => {         x.sweets.forEach(y => {           if (y === option){             this.checkedList.push(x);           }         });       });// this is the part that isn't working     } else {       this.checkedList.forEach(c, i => {         c.sweets.forEach(k => {           // if 'sweet' name = option, remove its array object           if (k === option) {             this.checkedList.splice(i, this.checkedList.length)           }         })         })      }     }}
查看完整描述

1 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

請找到解決問題的更簡單的方法


 onCheckboxChange(option, event) {

  let checkedState = event.target.checked;

  if(checkedState === true)

    this.checkedList = this.checkedList.concat(this.grocery_list.filter(item => item.sweets.includes(option)))

  else

    this.checkedList = this.checkedList.filter(item => !item.sweets.includes(option));

    // the above code checks for items which contains sweets array with selected option and keeps only those which doesn't

  }

更新 更改以下類型


checkedList: any[] = []; // or create an interface based on your grocery_list


查看完整回答
反對 回復 2021-11-12
  • 1 回答
  • 0 關注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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