![](/img/trans.png)
[英]How to push and remove item from an array on checked or unchecked of checkboxes?
[英]How to remove item from array 1 and push item to array 2
我嘗試的是檢查 state.newCardArray 並根據索引刪除該項目,然后將其推送到 state.arrayFoldedCards。 這是一個紙牌游戲,所以如果 newCardArray 為空並且沒有贏家或輸家,那么游戲就會停止......
const initialState = {
newCardArray: ['a', 'b', 'c']; // after removing the array looks like ['a', 'c']
arrayFoldedCards: [] // pushing to the array resulted in an updated array that looks like ['b']
}
export const game = (state = initialState, action) => {
switch (action.type) {
case types.GET_CARD:
{
const getRandomNumber = Math.floor(state.newCardArray.length * Math.random());
console.log(state.newCardArray);
console.log(state.arrayFoldedCards);
return {
...state,
randomNumber: getRandomNumber,
arrayFoldedCards: state.newCardArray[getRandomNumber].push(state.arrayFoldedCards.pop())
}
}
}
}
看起來你想要像 splice/concat 這樣的東西
var idxToRemove = 1; //Removing 'b'
var arr0 = ['a', 'b', 'c'];
var arr1 = []; //Array to move to
return arr1.concat(arr0.splice(idxToRemove, 1));
Splice 返回一個已刪除元素的數組,以便您可以將它們連接在一起。 Concat 合並兩個數組而不發生變異。
case types.GET_CARD: { const indexToRemove = Math.floor(state.currentCardArray.length * Math.random()); const updatedArray = state.arrayFoldedCards.concat(state.currentCardArray.splice(indexToRemove, 1)); return { ...state, arrayFoldedCards: updatedArray } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.