【发布时间】:2019-11-13 10:15:26
【问题描述】:
我的脚本有问题。它从 url 解析 SVG 并将数据作为日志发送到控制台。它发回的字符串在谷歌控制台中看起来像这样:[346,453,346,452,346,452,346,453,346,453,347,453,347,453,347,454,348,454,349,454,350,454,351,454,352,454,353,454,354,454,354,453,355,452,355,453]
对于每一对,我需要将这个字符“[”添加到对的开头,并将这个字符“]”添加到对的末尾。
所以它会记录类似这样的数据:[[346,453],[346,452],[346,452],[346,453],[346,453],[347,453],[347,453],[347,454],[348,454],[349,454],[350,454],[351,454],[352,454],[353,454],[354,454],[354,453],[355,452],[355,453]]
这是我尝试过的。
我的功能:
const polylines = Array.from(xmlDoc.getElementsByTagName('polyline'));
polylines.map(
pl => pl.getAttribute('points').split(' ').map(
pair => pair.split(',').map(x=>+x),
var paired = ("[" + (x=>+x) + "]"), // Tried adding "(x=>+x)" - result huge error.... Can't use a variable there??
console.log("[" + paired + "]")
正如我所料,这很快就以错误告终。 我似乎无法找到让我的脚本执行此操作的方法...如果您可以提供帮助,请执行此操作。这不是任何形式的重复帖子。我需要这个以特定方式登录控制台,这在此处的其他帖子中找不到。
完整脚本:(当前)
xhr=new XMLHttpRequest();
// Tell the request where the file is.
xhr.open("GET", "http://URLHERE.com/blah.svg");
// Add event handler to process the file once it's been fetched.
xhr.addEventListener("load", function() {
// Once the text is available, create an XML parser
// and parse the text as an SVG image.
const xmlDoc = new DOMParser().parseFromString(
this.responseText.trim(),
"image/svg+xml"
);
// xmlDoc.getElements() returns something Array-like, but not an Array.
// This turns it into an Array.
const polylines = Array.from(xmlDoc.getElementsByTagName('polyline'));
var Lines = (polylines.map(
pl => pl.getAttribute('points').split(' ').map(
pair => pair.split(',').map(x=>+x), //<<<< seperates the comma between each split.
console.log("[" + pl.getAttribute('points') + "]") // Adds the "[", "]" to the front and back and logs the lines.
)
));
});
xhr.send();
【问题讨论】:
-
如果您想成对获取数组元素,请尝试在常规 for 循环中增加 2。像这样
for(var i=0; i<polyline.length; i=i+2) { console.log(polyline[i], polyline[i+1]) } -
登录谷歌控制台时。我希望它记录如下内容:
[[346,453],[346,452],[346,452],[346,453],[346,453],[347,453],[347,453],[347,454],[348,454],[349,454],[350,454],[351,454],[352,454],[353,454],[354,454],[354,453],[355,452],[355,453]] -
现在它在谷歌的控制台中记录如下:
[346,453,346,452,346,452,346,453,346,453,347,453,347,453,347,454,348,454,349,454,350,454,351,454,352,454,353,454,354,454,354,453,355,452,355,453]。 -
我认为你可以用上面的 for 循环替换
var Lines = ...块。 -
"272,437 274,437 274,437 275,437 275,437 277,438 277,438 280,439 280,439 281,440 281,440 282,440 283,440 284,440 285,439 286,438 287,438 287,437 287,436 287,435 288,434"认为这是您调用pl.getAttribute('points')时返回的字符串。它返回给我这个["272,437", "274,437", "274,437", "275,437", "275,437", "277,438", "277,438", "280,439", "280,439", "281,440", "281,440", "282,440", "283,440", "284,440", "285,439", "286,438", "287,438", "287,437", "287,436", "287,435", "288,434"]然后你像这样再次映射.map(arg => console.log('['+arg+']'));
标签: javascript xmlhttprequest tampermonkey