[英]How to remove item from array 1 and push item to array 2
What I try is to check the state.newCardArray and remove that item based on index and then push it to state.arrayFoldedCards.我尝试的是检查 state.newCardArray 并根据索引删除该项目,然后将其推送到 state.arrayFoldedCards。 This is a card game, so if the newCardArray is empty and there is no winner or loser, then the game stops....
这是一个纸牌游戏,所以如果 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())
}
}
}
}
Looks like you want something like splice/concat看起来你想要像 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 returns an array of removed elements so you can concat them together. Splice 返回一个已删除元素的数组,以便您可以将它们连接在一起。 Concat merges the two arrays without mutating either.
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.