数组和检查其中的值有问题

  • 本文关键字:有问题 数组 javascript
  • 更新时间 :
  • 英文 :


你好,最近我在JavaScript中使用数组,但函数出现了一个小问题。

我的问题是在功能checkRepeat中,在这个函数中,我试图知道我之前是否点击了一张卡,当我点击第一张卡工作但其他卡它们不起作用时,我在想我的问题可能是循环,因为也许它只需要一个元素,但我不知道。

这是我的代码:

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();

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

因为当它遍历数组时,它会找到一个相等的值,但它继续遍历数组,而其他值与比较值不同,因此它稍后会在数组中添加相同的值。

我解释:

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

例:

我单击第一个元素,[0] 被保存,我单击第二个 [0,1] 并再次给出第二个元素,当将 0 与 1 进行比较时,我发现它们是不同的,当它应该只返回 [0,1] 时,它仍然像这样 [0,1,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;
}
}

最新更新