【问题标题】:Create table dynamically in JavaScript with map function使用 map 函数在 JavaScript 中动态创建表
【发布时间】:2022-01-20 22:06:54
【问题描述】:

我正在尝试使用映射函数在 JavaScript 中动态创建表,但出现错误。谁能指点一下?

Uncaught SyntaxError: Invalid shorthand property initializer

这是我的代码:

// List of movies
let movies = [
    {
        title: "Fight Club",
        rank: 10,
        id: "tt0137523"
    },
    {
        title: "The Shawshank Redemption",
        rank: 1,
        id: "tt0111161"
    }
    
]


function displayMovies(movies){
   let table = '<table>';
   table += `<tr><th>ID</th><th>Name</th><th>Rank</th></tr>`;
   movies.map((movie, index) => ({
       table = table + `<tr>`,
       table = table + `<td>` + `Title:` `${movie.id}` + `</td>`,
       table = table + `<td>` + `Title:` `${movie.title}` + `</td>`,
       table = table + `<td>` + `Title:` `${movie.rank}` + `</td>`
    }));  
    table += "</table>"
    document.getElementById("movies-list").innerHTML = table;
}

displayMovies(movies);
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <!-- <script src="script.js"></script> -->
    <script src="demo.js"></script>
    <div id="movies-list">
      <!-- The div element where the movies table will be inserted --> 
    </div>
  </body>
</html>

【问题讨论】:

  • =&gt; ({ 替换为=&gt; {。在您的行中使用map。如果你使用({ ...}),它认为你想要返回一个对象。
  • 并将.map() 更改为.forEach()(虽然它仍然可以与地图一起使用,但如果您不使用.map 的返回值,则可以使用forEach)

标签: javascript


【解决方案1】:
  1. 您需要在displayMovies 函数上使用Array.forEach 而不是Array.mapArray.map 用于创建一个新数组,其中填充了在调用数组中的每个元素上调用提供的函数的结果。不需要基于movies数组返回一个新数组,所以最好使用Array.forEach

  2. 在循环中添加 td 值时语法错误。

table = table + `<td>` + `Title:` `${movie.id}` + `</td>`,

应该替换为

table = table + `<td>Title: ${movie.id}</td>`;

所以删除最后的','并在Title: ${movie.id}之间使用运算符或按上述方式进行。

// List of movies
let movies = [
    {
        title: "Fight Club",
        rank: 10,
        id: "tt0137523"
    },
    {
        title: "The Shawshank Redemption",
        rank: 1,
        id: "tt0111161"
    }  
];

function displayMovies(movies){
   let table = '<table border="1">';
   table += `<tr><th>ID</th><th>Name</th><th>Rank</th></tr>`;
   movies.forEach((movie, index) => {
       table = table + `<tr>`;
       table = table + `<td>Title: ${movie.id}</td>`;
       table = table + `<td>Title: ${movie.title}</td>`;
       table = table + `<td>Title: ${movie.rank}</td>`;
       table += `</tr>`;
    });
    table += "</table>";
    document.getElementById("movies-list").innerHTML = table;
}

displayMovies(movies);
&lt;div id="movies-list"&gt;&lt;/div&gt;

【讨论】:

  • 谢谢!我将您的代码粘贴到我的编辑器中,但现在我收到此错误 Uncaught TypeError: Cannot set property 'innerHTML' of null
  • 尝试把id名改成movieslist试试。
【解决方案2】:

您有几个语法错误。

demo.js 中,对于不需要插值的字符串文字,我使用了单引号而不是反引号。您还缺少几个 + 运算符。另外,在index.html 中,我将&lt;script&gt;...&lt;/script&gt; 标签移到了“movies-list” div 下方。

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <!-- <script src="script.js"></script> -->
    <div id="movies-list">
      <!-- The div element where the movies table will be inserted --> 
    </div>
    <script src="demo.js"></script>
  </body>
</html>

demo.js

// List of movies
let movies = [
    {
        title: "Fight Club",
        rank: 10,
        id: "tt0137523"
    },
    {
        title: "The Shawshank Redemption",
        rank: 1,
        id: "tt0111161"
    }
    
]


function displayMovies(movies){
   let table = '<table>';
   table += '<tr><th>ID</th><th>Name</th><th>Rank</th></tr>';
   movies.map((movie, index) => {
       table = table + '<tr>',
       table = table + '<td>' + 'Title:' + `${movie.id}` + '</td>',
       table = table + '<td>' + 'Title:' + `${movie.title}` + '</td>',
       table = table + '<td>' + 'Title:' + `${movie.rank}` + '</td>'
    });  
    table += "</table>"
    document.getElementById("movies-list").innerHTML = table;
}

displayMovies(movies);

【讨论】:

    【解决方案3】:

    从数据中显示顺序正常的动态示例

    我想在 React 中创建类似的东西。仍然想在这里添加一个更动态的答案,也许它对某些人来说可能会派上用场。

    脚本获取电影并从中创建头部标题和内容。 createHead 函数需要一个电影对象,只需获取键,使每个标题的第一个字符大写,并用 tr 和 th 包装所有标题。

    createRow 函数对内容部分的作用几乎相同,但没有大写部分,而是采用每个电影对象属性的值而不是键。该函数在 createTable 函数中进行迭代,并使用 map 函数将新创建的行存储在 const 中:

    const rows = movies.map((movie) => {
      return createRow(movie)
    });
    

    CodePen example here

    同样的例子在这里内联:

    const movies = [
        {
            title: "Fight Club",
            rank: 10,
            id: "tt0137523"
        },
        {
            title: "The Shawshank Redemption",
            rank: 1,
            id: "tt0111161"
        }
    ];
    
    // Creates the table head entries. Simply gets the first movie and takes the keys as titles
    const createHead = (headObject) => {
        let cells = "";
        for (const key in headObject) {
          // This takes the first letter of each title and uppercases it
          cells += `<th>${key.charAt(0).toUpperCase() + key.slice(1)}</th>`;
        }
    
        return `<tr>${cells}</tr>`;
    };
    
    // Creates the content entries
    const createRow = (rowObject) => {
        let cells = "";
        for (const key in rowObject) {
          cells += `<td>${rowObject[key]}</td>`;
        }
    
        return `<tr>${cells}</tr>`;
    };
    
    // Main function to create it all
    const createTable = (movies) => {
        const rows = movies.map((movie) => {
          return createRow(movie)
        });
      
        // Creates the table head titles
        const headRow = createHead(movies[0])
        
        // Takes the rows and concats again to prevent some weird commas from appearing?
        let optimizedRows = ''
        rows.forEach((row) => {
          optimizedRows += row;
        });
    
        // This finally combines table, head and body contents
        const table = (`
          <table>
            <thead>${headRow}</thead>
            <tbody>${optimizedRows}</tbody>
          </div>
        `);
    
        document.getElementById("movies-list").innerHTML = table;
    };
    
    createTable(movies);
    &lt;div id="movies-list"&gt;Loading movies ...&lt;/div&gt;

    【讨论】:

      【解决方案4】:

      您可以使用相同的 HTML

      <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width">
          <title>repl.it</title>
          <link href="style.css" rel="stylesheet" type="text/css" />
        </head>
        <body>
          <!-- <script src="script.js"></script> -->
          <script src="demo.js"></script>
          <div id="movies-list">
            <!-- The div element where the movies table will be inserted --> 
          </div>
        </body>
      </html>
      

      demo.js 你可以试试这个:

      const movies = [
          {
              title: 'Fight Club',
              rank: 10,
              id: 'tt0137523',
          },
          {
              title: 'The Shawshank Redemption',
              rank: 1,
              id: 'tt0111161',
          }
      ];
      
      const displayMovies = () => {
        let table = '<table border="1">';
        table += '<tr><th>ID</th><th>Name</th><th>Rank</th></tr>';
        movies.forEach((movie) => {
          table += `<tr>
                      <td>Title: ${movie.id}</td>
                      <td>Title: ${movie.title}</td>
                      <td>Title: ${movie.rank}</td>
                    </tr>`;
        });
        table += '</table>';
        document.getElementById('movies-list').innerHTML = table;
      };
      
      displayMovies();
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-13
        • 2011-07-24
        • 1970-01-01
        • 1970-01-01
        • 2013-08-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多