[英]JS: How do I use an element in an array and then get rid of it
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. 这就是卡片进入我的HTML的方式。
var cardIndexNum = Math.floor(Math.random() * 10);
var cardReturn = vocabArray[cardIndexNum];
document.getElementById('card1').innerHTML = '<h2>' + cardReturn.hanyu + '<br>' + cardReturn.pinyin + '</h2>';
HTML 的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.
使用卡后,我尝试在卡上使用.splice,但是有时我会得到带有未定义属性的数组元素。
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 ) (此示例使用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 您需要传递
vocabArray
以及id
和value
作为函数参数
findAndRemove(vocabArray, "id", 1);
EDIT 编辑
To support normal javascript 支持普通的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.