我有一个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();
})
}
答案 0 :(得分:1)
也许您正在记录错误的变量:
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();
})
}
答案 1 :(得分:0)
从技术上来说应该是
console.log(sound.sound)
可能想更改那些变量名
如果要提取声音,请输入动物类型...
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 results = sounds.filter(function(cv,i){
return (cv.animalType==='goat') ? cv.sound : false;
})
console.log(results[0])