例如,假设我想要一组随机播放的歌曲,输出歌曲标题。
var myArray = ['song1', 'song2', 'song3'];
var random = myArray[Math.floor(Math.random() * myArray.length)];
document.write(random);
但如果我也想要那首歌专辑封面加上艺术家的描述,这可能吗?我想如果我要将每一个单独手动添加到我的代码中,但如果我想要1000首歌曲怎么办呢?
答案 0 :(得分:1)
避免使用document.write
。通过将每个Song对象放入Array中,您可以实现:
var myArray = [{title:'Song 1 Title', artist:'Song 1 Artist'}, {title:'Song 2 Title', artist:'Song 2 Artist'}, {title:'Song 3 Title', artist:'Song 3 Artist'}];
function getRandomSong(ary){
return ary[Math.floor(Math.random()*ary.length)];
}
var randomSong = getRandomSong(myArray);
console.log(randomSong.title); console.log(randomSong.artist);
当然,如果您有数千首歌曲,您可能希望在数据库上执行类似Sever Side的内容。在PHP中,这可能看起来像:
<?php
class Song{
private $db; public $currentSelection;
public function __construct($databaseConnection){
$this->db = $databaseConnection;
$this->currentSelection = $this->getRandomSong();
}
public function getRandomSong(){
$db = $this->db;
if($sq = $db->query('SELECT COUNT(*) count FROM songTable')){
if($sq->num_rows > 0){
$c = $sq->fetch_object(); $rc = rand(1, $c->count);
if($rq = $db->query("SELECT * FROM songTable WHERE primaryKey=$rc"){
if($rq->num_rows > 0){
return json_encode($rq->fetch_assoc());
}
else{
// no rows
}
$rq->free();
}
else{
// connection failure
}
}
else{
// no rows
}
$sq->free();
}
else{
// connection failure
}
return false;
}
}
$songObj = new Song($databaseConnectionHere);
echo $songObj->currentSelection;
echo $songObj->getRandomSong();
$dataBaseConnectionHere->close();
?>