简体   繁体   English

使用split分隔数组中的元素,JavaScript

[英]Using split to seperate elements in an array, JavaScript

I am seeking to create a table that will take an array with 3 items separated by commas and have them inserted in to a table. 我正在尝试创建一个表,该表将采用3个由逗号分隔的项组成的数组并将其插入表中。 Currently my table either fails, or will present the items all grouped together. 目前,我的表格要么失败,要么将所有项目组合在一起。 Under each heading I have one row each filled with "Madrid,Spain,3255944", "Santiago,Chile,4837295", "Lima,Peru,7737002" under the three headings of Country, Capital, Population, I would like 3 rows separated for each heading. 在每个标题下的国家,首都,人口这三个标题下,我每一行分别填充着“马德里,西班牙,3255944”,“圣地亚哥,智利,4837295”,“利马,秘鲁,7737002”,我想分开三行每个标题。

 <html> <head> <title> </title> <meta charset="windows-1252"> <meta name="viewport" content="width=device-width, initial- scale=1.0"> </head> <body> <table id="table" border="1"> <!-- The Row Number 0 --> <tr> <th>City</th> <th>Country</th> <th>Population</th> </tr> </table> <script> var array = [ ["Madrid,Spain,3255944", "Santiago,Chile,4837295", "Lima,Peru,7737002"], ], var a = array.split(',') a[0], a[1], a[2]; table = document.getElementById("table"); for(var i = 0; i < array.length; i++) { // create a new row var newRow = table.insertRow(table.length); for(var j = 0; j < array[i].length; j++) { // create a new cell var cell = newRow.insertCell(j); // add value to the cell cell.innerHTML = array[i][j]; } } </script> </body> </html> 

You need to call split() on the strings in the array, not the array itself. 您需要在数组中的字符串上调用split() ,而不是数组本身。

array.forEach(row => {
    cols = row.split(",");
    newRow = table.insertRow(table.length());
    cols.forEach(col => {
        var cell = newRow.insertCell(newRow.length);
        cell.innerHTML = col;
    });
});

Barmars answer is certainly correct but beyond my ken, I do appreciate it. Barmars的回答当然是正确的,但是我不胜感激。 Another source provided the following which is slightly easier to grasp that worked for me beginner self. 另一个来源提供了以下内容,这些内容对于我的初学者来说比较容易理解。 Below is more towards the use of a learner such as myself and I will correct it and provide the full code once I complete my task, great thanks for the gentleman taking his time and I shall seek to learn my about the syntax when time allows. 下面是更多关于像我这样的学习者的使用,一旦完成任务,我将纠正它并提供完整的代码,非常感谢这位先生花时间,在时间允许的情况下,我将寻求学习语法。

            var array = [
        "Madrid,Spain,3255944", "Santiago,Chile,4837295", "Lima,Peru,7737002"
    ];
    table = document.getElementById("table");

var x;
for (var i = 0; i < array.length; i++){

    <tr>
        x = arr[i];
    var pieces = array.split(',');
    <td> pieces[0] </td> 
    <td> pieces[1] </td>
    <td> pieces[2] </td>
</tr>;

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM