JS - 将数组打印到 DOM

问题描述 投票:0回答:1

将过滤后的数组打印到 DOM 的好方法是什么?我正在尝试为 onclick 创建一个函数 (printJazzAlbums()),将过滤后的数组打印到 DOM。如果我只是用 queryselector 打印它,它会显示 [object],如果我先 JSON.stringify 它,它看起来会因为所有大括号而变得混乱,并且格式不正确(项目之间没有换行符)。谢谢!

<script>
    const records = [
      {
        artist: 'Miles Davis',
        album: 'Kind of Blue',
        label: 'Columbia',
        year: 1959,
        genre: 'Jazz'
      },
      {
        artist: 'Ralph Stanley',
        album: 'Old Home Place',
        label: 'Rebel',
        year: 1976,
        genre: 'Bluegrass'    
      },
      {
        artist: 'Bad Religion',
        album: 'No Control',
        label: 'Epitaph',
        year: 1989,
        genre: 'Punk Rock'
      },
      {
        artist: 'John Coltrane',
        album: 'A Love Supreme',
        label: 'Impulse!',
        year: 1965,
        genre: 'Jazz'
      },
      {
        artist: 'Descendants',
        album: 'Milo Goes to College',
        label: 'New Alliance',
        year: 1982,
        genre: 'Punk Rock'
      },
      {
        artist: 'Charles Mingus',
        album: 'Town Hall Concert',
        label: 'Jazz Workshop',
        year: 1959,
        genre: 'Jazz'
      },
      {
        artist: 'Tony Rice',
        album: 'Manzanita',
        label: 'Rounder',
        year: 1979,
        genre: 'Bluegrass'
      },
      {
        artist: 'Ornette Coleman',
        album: 'The Shape of Jazz to Come',
        label: 'Atlantic',
        year: 1959,
        genre: 'Jazz'
      },
      {
        artist: 'Joni Mitchell',
        album: 'Blue',
        label: 'Reprise',
        year: 1971,
        genre: 'Rock'
      },
      {
        artist: 'Pat Martino',
        album: 'El Hombre',
        label: 'Prestige',
        year: 1967,
        genre: 'Jazz'
      },
      {
        artist: 'Roy Haynes',
        album: 'Out of the Afternoon',
        label: 'Impulse!',
        year: 1962,
        genre: 'Jazz'
      },
      {
        artist: 'Neil Young',
        album: 'Harvest',
        label: 'Reprise',
        year: 1972,
        genre: 'Rock'
      },
    ];


    function printJazzAlbums() {
      document.querySelector('#print-albums').innerHTML = 
      JSON.stringify(jazzAlbums);
    }

    const jazzAlbums = records.filter(record => record.genre === 'Jazz');
    
    
  </script>
javascript arrays dom filter
1个回答
0
投票

要以更易于理解的格式将过滤后的数组打印到 DOM,您可以循环遍历该数组并为要显示的每个项目创建 HTML 元素。

或者您可以使用外部库来格式化数据,例如 code-prettify

© www.soinside.com 2019 - 2024. All rights reserved.