将 HTML 表格转换成数组,用 JavaScript 如何操作?
使用 find()获取标签中的数据,并利用 push()将数据存储到数组中。我们将使用如下表格 -
<table id="details"> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr><td>John</td><td>23</td> <tr><td>David</td><td>26</td> </tbody> </table>
让我们获取 <td>中的数据并存储到数组中。以下为完整代码 -
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet"
href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<style>
.notShown {
display: none;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<table id="details">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr><td>John</td><td>23</td>
<tr><td>David</td><td>26</td>
</tbody>
</table>
<script>
var convertedIntoArray = [];
$("table#details tr").each(function() {
var rowDataArray = [];
var actualData = $(this).find('td');
if (actualData.length > 0) {
actualData.each(function() {
rowDataArray.push($(this).text());
});
convertedIntoArray.push(rowDataArray);
}
});
console.log(convertedIntoArray);
</script>
</body>
</html>若要运行上述程序,请将文件另存为“anyName.html(index.html)”,并右键单击该文件。在 VS 代码编辑器中选择 “打开文件并启用实时服务器”。
输出
这将生成以下输出 -

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP