我对此进行了很多谷歌搜索,并且我知道有一些方法可以复制数组并在不影响原始数组的情况下使用它们,但是我确实尝试了很多东西,但在我的特定代码行上似乎没有任何效果。
我正在做一个简单的记忆游戏。当用户获得正确的配对时,匹配配对的图像将出现在右侧屏幕上,显示用户获得的所有匹配图像。下图显示了这一点,但是当我使用一种方法来调整图像大小时(匹配的对比普通游戏卡小),我选择了未定义的卡cardState。
这是一堆代码,可以帮助您解决我的问题:
checkCardSelection(_cardSelectionArray,_position){
var _cardArray = this.state.cardArray;
var _matchedcardArray = this.state.matchedcardArray;
console.log("Position:" +_position)
if(_cardSelectionArray[0].cardType === _cardSelectionArray[1].cardType){
var copy = _cardSelectionArray.slice(0,1)
_matchedcardArray.push(copy)
_matchedcardArray[_matchedcardArray.length-1].cardState = this.renderMatchedImage(_matchedcardArray[_matchedcardArray.length-1].cardType)
this.setState({ cardArray: _cardArray, matchedcardArray: _matchedcardArray });
renderMatchedImage(cardType) {
switch(cardType) {
case 'A':
return <img src={imagem1} alt="Raposa" width="49px" height="70px"/>;
case 'B':
return <img src={imagem2} alt="Cobra" width="49px" height="70px"/>;
case 'C':
return <img src={imagem3} alt="Galinha" width="49px" height="70px"/>;
// and so on...
MatchedCardArray是一个空数组,一旦它们配对就会得到卡片
CardSelectionArray是一个双值数组,其中选择了两对
每张卡片都有一个CardType(A,B,C,D,...)和一个CardState(“不可见”或返回的图像)。它们是随机的,具有函数。例如,CardArray可能是:
0: {cardType: "G", cardState: "INVISIBLE"}
1: {cardType: "B", cardState: "INVISIBLE"}
2: {cardType: "A", cardState: "INVISIBLE"}
