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

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

如何避免將重復項添加到數組中,并且特定屬性一次只有一個值?

如何避免將重復項添加到數組中,并且特定屬性一次只有一個值?

慕少森 2022-05-26 16:20:57
我有一些CalendarIcons看起來像鏈接中的圖片。這些圖標有這些 id:autumn=2020-08-20autumn=2020-08-22spring=2020-04-20spring=2020-04-21我創建了一個數組來保存日期:const selectedDates = []在我的狀態。當我選擇一個日期時,我可以將id值推送到selectedDates數組中。當我選擇一個圖標時,我得到 id:autumn=2020-08-20并推送到我的selectedDates數組。但是,如果我單擊具有此 ID 的另一個圖標:autumn=2020-08-22它也被推送到數組中。但我只想要一個autumn值,并且只想要spring我的數組中的一個值。我該如何解決,所以我的數組只包含autumnor的一個值spring?這是我的 handleClicked 方法CalendarIcons:handleClicked(calendarIconId, rowLabelId) {    // Should not add same value autumn, spring, etc. again, and only add one value specificed behind the =    var dateArray = this.state.selectedDates.concat(calendarIconId);    this.setState({        calendarSelectedIconId: calendarIconId,        rowTracker: rowLabelId,        selectedDates: dateArray    });}我希望問題很清楚,如果問題不清楚,請給我反饋。感謝您的幫助!
查看完整描述

2 回答

?
Helenr

TA貢獻1780條經驗 獲得超4個贊

Set將自動使值唯一。你可以有類似的東西:

// Declaration of the Set

const uniqueSet = new Set();


function handleClicked(calendarIconId) {

  // Add the new value inside of the Set

  uniqueSet.add(calendarIconId);

  

  // Turn the set into an array

  const array = Array.from(uniqueSet);


  console.log(array);

}


handleClicked('autumn=2020-08-20');

handleClicked('autumn=2020-08-22');

handleClicked('autumn=2020-08-22');

handleClicked('autumn=2020-08-22');

handleClicked('autumn=2020-08-22');

handleClicked('autumn=2020-08-22');

handleClicked('spring=2020-04-20');

handleClicked('spring=2020-04-21');

handleClicked('spring=2020-04-21');

handleClicked('spring=2020-04-21');

handleClicked('spring=2020-04-21');

handleClicked('spring=2020-04-21');

編輯:我們只想為每個季節保留一個值:


// Declaration of an object. We are going to use the key/value system

const library = {};


function handleClicked(calendarIconId) {

  // We "open" the value to extract the relevant informations

  const [

    key,

    value,

  ] = calendarIconId.split('=');


  // Add the new value inside of the object

  library[key] = value;

  

  // Turn the object into an array, we gotta rebuild the values

  const array = Object.keys(library).map(x => `${x}=${library[x]}`);


  console.log(array);

}


handleClicked('autumn=2020-08-20');

handleClicked('autumn=2020-08-22');

handleClicked('autumn=2020-08-22');

handleClicked('autumn=2020-08-22');

handleClicked('autumn=2020-08-22');

handleClicked('autumn=2020-08-22');

handleClicked('spring=2020-04-20');

handleClicked('spring=2020-04-21');

handleClicked('spring=2020-04-21');

handleClicked('spring=2020-04-21');

handleClicked('spring=2020-04-21');

handleClicked('spring=2020-04-21');


查看完整回答
反對 回復 2022-05-26
?
DIEA

TA貢獻1820條經驗 獲得超3個贊

你可以做


if(!Array.includes(id)) {

  Array.push(id)

}


查看完整回答
反對 回復 2022-05-26
  • 2 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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