首页 > 解决方案 > 数组和检查里面的值的问题

问题描述

您好,最近我正在使用 JavaScript 中的数组,并且出现了一个函数的小问题。

我的问题出在函数checkRepeat中,在这个函数中,我试图知道我是否之前点击过一张卡片,当我点击第一张卡片但其他卡片不起作用时,我在想我的问题可能是for 循环,因为它可能只占用一个元素,但我不知道。

这是我的代码:

const cardArray = [
    {name: 'fries'},
    {name: 'pizza'},
    {name: 'hotdog'},
    {name: 'cheeseburger'},
    {name: 'milkshake'},
    {name: 'ice-cream'}
]
const emptyCard = [
    {name: 'white'},
    {name: 'blank'}
]
// the format of the img
const format = '.png'
// I select the place where I gonna put the board
const grid = document.querySelector('.grid');
const cardsChosen = [];
const cardsChosenId = [];


const createBoard = () =>{
    for(let n = 0; n < cardArray.length*2; n++)
    {
        // I create the img
        let card = document.createElement('img');
        card.src = `images/${emptyCard[1].name}${format}`;
        card.id = `card-${n}`
        card.addEventListener('click',flipCard)
        grid.appendChild(card)
    }
}

function flipCard(){
    // I get the id, just the number
    let cardId = parseInt(this.getAttribute('id').slice(5,7));
    const v1 = checkRepeat(cardsChosenId,cardId);
    console.log("Value: ",v1)
    //console.log("Values in the array: ",cardsChosenId)
}

function checkRepeat(array,value){
    if(array.length === 0){// if the array is empty
        array.push(value);//push in the array the value
        return true;// and return true
    }
    else{// if isn't
        for(let i = 0; i < array.length; i++){// walk through the array
            if(array[i] === value){// check if the values of the array === value
                return false;
            }
            else{// if the value and the array values are different
                array.push(value);//push the value
                return true;
            }
        }
    }
}

createBoard();

标签: javascript

解决方案


我在代码中发现了错误,问题是逻辑。

因为它在遍历数组的时候,找到了一个相等的值,但是它继续遍历数组并且其他的值和比较的值不相似,所以它在后面的数组中添加了相同的值给我。

我解释:

当我点击每张卡片时,它们会将 id 保存在一个排列中,如果我再次点击我之前给它的卡片,它将与每个元素进行比较,当它找到相同的元素时,它将返回 false ,但继续滚动整个排列并在我不应该有的时候向排列添加更多元素。

例子:

我点击第一个元素,[0] 被保存,我点击第二个 [0,1] 并再次给出第二个元素,当比较 0 和 1 时,我发现它们是不同的,它仍然像这样 [0, 1,1] 当它应该只返回 [0,1]

我解决包括:

function checkRepeat(array,value){
   if(array.includes(value)){//return true if value it's in the array
        return false;
    }
    else{
        array.push(value);
        return true;
    }
}


推荐阅读