JavaScript:是否可以将图像/信息附加到数组项

JavaScript: Is it possible to attach images/information to an array item?

本文关键字:信息 数组 图像 是否 JavaScript      更新时间:2023-09-26

例如,假设我想要一个随机的歌曲数组,输出一个歌曲标题。

  var myArray = ['song1', 'song2', 'song3'];
  var random = myArray[Math.floor(Math.random() * myArray.length)];
  document.write(random);

但如果我也想要歌曲专辑封面加上艺术家的描述,那可能吗?我想如果我手动将每首歌单独添加到我的代码中,但如果我想要1000首歌呢?

避免document.write。通过将每个歌曲对象放入你的数组中,你可以实现这一点:

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();
?>