首页 > 解决方案 > 当我调用它时,如何“自动化”我的程序来运行每个对象

问题描述

我想要解决的是调用函数内部的对象名称之一,它应该打印信息,我尝试了不同的方法,但似乎找不到一个很好的解决方法来自动化它。

const usAlbania = {
    name: "United States of Albania",
    artist: "Mc Kresha, Lyrical Son, Lluni",
    type: "Hip-Hop",
    songs: "23",
    year: "2019"
};

const ybnMixtape = {
    name: "YBN Mixtape",
    artist: "YBN Nahmir, YBN Almighty Jay, YBN Cordae",
    type: "Rap & Hip-hop",
    songs: "17",
    year: "2018"
};

const astroWorld = {
    name: "Astro World",
    artist: "Travis Scott",
    type: "Rap",
    songs: "13",
    year: "2018"
};

const albums = {
    usAlbania: usAlbania,
    ybnMixtape: ybnMixtape,
    astroWorld: astroWorld
}

function albumShow () {
    const html = `
        <p><img src="images/USA.jpg" height="200"></p>
        <p class="albumName">Album Name: ${albums}</p>
        <p class="artist">Artist: ${albums}</p>
        <p class="type">Grenre: ${albums}</p>
        <p class="songs">Album Songs: ${albums}</p>
        <p class="year">Album Year: ${albums}</p>
    `
    const showAlbumInfo = document.querySelector('.albumInfo');
    showAlbumInfo.innerHTML = html;
}

albumShow()

标签: javascript

解决方案


这是您可以做到的一种方法:

let aryAlbums = [];
const usAlbania = {
    name: "United States of Albania",
    artist: "Mc Kresha, Lyrical Son, Lluni",
    type: "Hip-Hop",
    songs: "23",
    year: "2019"
};
aryAlbums.push(usAlbania);

const ybnMixtape = {
    name: "YBN Mixtape",
    artist: "YBN Nahmir, YBN Almighty Jay, YBN Cordae",
    type: "Rap & Hip-hop",
    songs: "17",
    year: "2018"
};
aryAlbums.push(ybnMixtape);

const astroWorld = {
    name: "Astro World",
    artist: "Travis Scott",
    type: "Rap",
    songs: "13",
    year: "2018"
};
aryAlbums.push(astroWorld);

function albumShow(album)
{
  return `
    <p><img src="http://www.neartalk.com/ss/usaCD.jpg" height="200"></p>
    <p class="albumName">Album Name: ${album.name}</p>
    <p class="artist">Artist: ${album.artist}</p>
    <p class="type">Grenre: ${album.type}</p>
    <p class="songs">Album Songs: ${album.songs}</p>
    <p class="year">Album Year: ${album.year}</p>
  `;
}

let aryHTML = aryAlbums.map(albumShow);

let allHTML = aryHTML.join("\n");
document.body.innerHTML = allHTML;


推荐阅读