Javascript 从for循环中的数组中获取随机值(角度2)
我正在创建一个音板,当一个按钮被点击时,它会播放一个随机的声音。我试图通过在for循环中创建一个数组来实现这一点,该数组获取所有mp3文件链接文件名,当用户单击按钮时,文件名将使用Math.floorMath.random进行更改 我遇到的问题是,它只是播放相同的声音。它不会发出随机的声音 音板Javascript 从for循环中的数组中获取随机值(角度2),javascript,arrays,angular,typescript,ionic2,Javascript,Arrays,Angular,Typescript,Ionic2,我正在创建一个音板,当一个按钮被点击时,它会播放一个随机的声音。我试图通过在for循环中创建一个数组来实现这一点,该数组获取所有mp3文件链接文件名,当用户单击按钮时,文件名将使用Math.floorMath.random进行更改 我遇到的问题是,它只是播放相同的声音。它不会发出随机的声音 音板 似乎有一个逻辑错误。根据你对问题的描述,我认为你想要 export class Component { soundFileNames: string[] = []; media?: Audio
似乎有一个逻辑错误。根据你对问题的描述,我认为你想要
export class Component {
soundFileNames: string[] = [];
media?: Audio;
ngOnInit() {
for (const link of links) {
const fileName = link.getAttribute("href");
soundFileNames.push(fileName);
}
}
playRandomSoundFile() {
const randomIndex = Math.floor(Math.random() * soundFileNames.length);
const randomFileName = soundFileNames[randomIndex];
console.log(randomFileName);
const audio = new Audio(randomFileName);
audio.load();
audio.play();
this.media = audio;
}
}
我觉得使用下划线JS库来实现这些常见功能总是更好的。在您试图从数组中获取随机值的情况下,可以实现如下所示
import * as _ from 'underscore';
getRandomElementFromArray (sounds) {
let randomNumber = _.random(0, sounds.length);
return sounds[randomNumber];
}
你的代码很难读。你的字体放错地方了。让rand:any=[filename];这是可怕的代码。另一方面,playsound{真的可以使用类型注释……无论如何,你不是说const randomSound=sounds[Math.floorMath.random*sound.file.length].file;this.media=new AudiorandomSound;还有,为什么rand初始化为一个包含一个元素的数组?
import * as _ from 'underscore';
getRandomElementFromArray (sounds) {
let randomNumber = _.random(0, sounds.length);
return sounds[randomNumber];
}