我有一个 div,当用户单击它时,它会播放随机动物的声音。我正在尝试提取当前的声音名称,以便稍后检查它是否与用户输入匹配。目前,我的代码仅从对象“goat”数组中提取一个值,并且它没有根据声音 mp3 显示animalType,我该如何提取当前正在播放的声音animalType 属性?
这是我的代码:
var sounds = [
{
animalType: 'horse',
sound: new Audio('../sounds/Horse-neigh.mp3')
},
{
animalType: 'bear',
sound: new Audio('../sounds/grizzlybear.mp3')
},
{
animalType: 'goat',
sound: new Audio('../sounds/Goat-noise.mp3'),
}
]
var player = document.getElementById('player');
var enteredWord = document.getElementById('entered-word');
var counter = document.getElementById('counter-score');
shuffleAnimalSound();
function shuffleAnimalSound() {
player.addEventListener('click', function() {
var sound = sounds[Math.floor(Math.random()*sounds.length)];
for(var i = 0; i < sounds.length; i++) {
var currentSound = sounds[i]
}
console.log(currentSound.animalType)
sound['sound'].play();
})
}
最佳答案
也许您记录的变量不正确:
var sounds = [
{
animalType: 'horse',
sound: new Audio('../sounds/Horse-neigh.mp3')
},
{
animalType: 'bear',
sound: new Audio('../sounds/grizzlybear.mp3')
},
{
animalType: 'goat',
sound: new Audio('../sounds/Goat-noise.mp3'),
}
]
var player = document.getElementById('player');
var enteredWord = document.getElementById('entered-word');
var counter = document.getElementById('counter-score');
shuffleAnimalSound();
function shuffleAnimalSound() {
player.addEventListener('click', function() {
var sound = sounds[Math.floor(Math.random()*sounds.length)];
/* for(var i = 0; i < sounds.length; i++) {
var currentSound = sounds[i]
}*/
console.log(sound.animalType)
sound['sound'].play();
})
}
关于javascript - 如何获取已打乱的对象数组的当前元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54240515/