以下代码具有一个名为additionalData
的数组,据认为该数组已填充数据。
如果我打印数组的长度,它将显示为0,这与我只是将数组本身记录到控制台工具中时所显示的信息形成鲜明对比,在控制台工具中可以按预期看到所有数据。
如果我尝试显示示例元素,它也会显示为undefined
。
也许对数组有更多帮助:
其内容类似于[ ["<a href=...> ... </a>"] , [...], ...]
这是浏览器控制台显示的数组本身:
[]
0: Array [ "<a href=https://www.openstreetmap.org/search?query=76139 Karlsruhe - Hagsfeld#map=12/49.0159/8.4097> 76139 Karlsruhe - Hagsfeld </a>" ]
1: Array [ "<a href=https://www.openstreetmap.org/search?query=nähe Bahnhof 75053 Gondelsheim -#map=12/49.0159/8.4097> nähe Bahnhof 75053 Gondelsheim - </a>" ]
....
39: Array [ "<a href=https://www.openstreetmap.org/search?query=Kirschstr. 17 76189 Karlsruhe - Daxlanden#map=12/49.0159/8.4097> Kirschstr. 17 76189 Karlsruhe - Daxlanden </a>" ]
length: 40
<prototype>: Array []
// ==UserScript==
// @name Table to CSV
// @version 1
// @grant none
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
// @require https://raw.githubusercontent.com/Toorero/table2CSV/master/table2CSV.js
// ==/UserScript==
function extractData(website_data) {
//get Node under which the adress is written
var node = $("b", website_data).filter( function (i, elem) {
return elem.innerText == "Standort:"
})[0].nextSibling;
//get the adress text (until next section => adress)
var addr_text = "";
do {
if(node.nodeName == "BR") addr_text +=" ";
else addr_text += node.textContent;
node = node.nextSibling;
} while (node.nodeName != "TABLE" && node.nodeName != "DIV")
addr_text = addr_text.replace("keine Angabe", "").trim();
const addr = `<a href=https://www.openstreetmap.org/search?query=${addr_text}#map=12/49.0159/8.4097> ${addr_text} </a>`;
return [addr];
}
$(document).ready(function () {
//get Data by following each link
var additionalData = [];
$("td > a").each(
function() {
$.get(this.search, function(data, status){ additionalData.push(extractData(data)) });
console.log('data from "' + this.search + '" retrieved!');
}
);
console.log(additionalData.length); // 0
console.log(additionalData); //displayed as expected
console.log(additionalData[4]); //undefined
console.log(additionalData[4]);
//add <td> element boundaries for collected data
const additionalColumns = additionalData.map( // <-- does not work because of the failure above
function(data) {
var r="";
for(x of data) {
r += `<td> ${r} </td>`;
}
console.log(r);
return r;
}
);
console.log(additionalColumns);
//insert the collected data
$(additionalColumns).insertAfter($("td > a").parent());
console.log("Inserted collected data!");
});