I'm trying to make a matching card game and trying to 'shuffle' my cards. Here is how I have everything set up right now:
Cards' data are objects
var idea = {
id: 1,
english: 'idea',
pinyin: 'zhǔyì',
hanyu: '主意'
}
The "deck" is an array with all the cards.
var vocabArray = [idea, getOn, need, getOff, beautiful, scenery, sameAlike, because, help, play];
This is how the cards are getting into my HTML.
var cardIndexNum = Math.floor(Math.random() * 10);
var cardReturn = vocabArray[cardIndexNum];
document.getElementById('card1').innerHTML = '<h2>' + cardReturn.hanyu + '<br>' + cardReturn.pinyin + '</h2>';
HTML
div class='card' id='card1'>
JAVASCRIPT PUTS CARD INFO AND H TAGS HERE
</div>
Right now I some cards are appearing more than once because after I use the card it is still in the array. I tried using .splice on the cards after they were used, but then I would sometimes get an array element with undefined attributes.
Since it is a array of objects , you can't use splice directly over the array inorder to remove the element.
(this example uses jQuery )
var findAndRemove = function(array, property, value) {
$.each(array, function(index, result) {
if(result[property] == value) {
array.splice(index, 1);
}
}
}
You need to pass vocabArray
and id
and value
as function parameter
findAndRemove(vocabArray, "id", 1);
EDIT
To support normal javascript
(NOT TESTED)
var findAndRemove = function(array, value) {
for(var i=0; i < array.length; i++) {
if(array[i].id == value) {
array.splice(i, 1);
}
}
}
Call by
findAndRemove(vocabArray, 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.