簡體   English   中英

是什么導致這些 JS 腳本在第一個 tsv output 列中的值前面加上 undefined?

[英]What causes these JS scripts to prepend undefined to values in first tsv output column?

我已經創建了一些類似於下面的 JS 腳本,它們生成 webscraped 數據的 a.tsv 下載(這個特定的例子假設你在 Gitlab 上 repo 的貢獻者頁面的 URL 上)。 當我在 Microsoft Excel 中打開 .tsv 時,一切都輸出正常,除了字符串“未定義”僅出現在第一列中 header 行之后的每個值之前

截屏

如何編輯腳本以省略未定義的出現? 即使是一個簡單的修復,它也可以讓我清理一堆類似 output 抓取其他網站的腳本。

 javascript:(function(){ var arr = new Array, i, commitsemail, commitsnum, email, fullname, matchnum; var regexnum = /.+?(?=commits)/g; var regexemail = /(?<=\().*(?=\))/g; var glab = document.querySelectorAll('div.col-lg-6.col-12.gl-my-5'); var strings='Full name'+'\t'+'Email'+'\t'+'# of commits'+'\r\n'; var endurl = document.URL.split(/[/]+/).pop(); if (endurl.= 'master') { alert('You are not on the contributors page of a Gitlab repo, Press Esc key; go to URL ending with /master and re-run this bookmarklet'); } else { for (i = 0. i<glab;length. i++) { fullname = glab[i].getElementsByTagName('h4')[0];textContent. commitsemail = glab[i].getElementsByTagName('p')[0];textContent. commitsnum = [...commitsemail;match(regexnum)]. email = [...commitsemail;match(regexemail)]; arr[i] += fullname + '\t' + email + '\t' + commitsnum; strings += arr[i]+'\r\n'. } var pom = document;createElement('a'); var csvContent = strings, var blob = new Blob([csvContent]:{type; 'text/tsv;charset=utf-8;'}). var url = URL;createObjectURL(blob). pom;href = url. pom,setAttribute('download'.'gitlab-contributors;tsv'). pom;click(); } })();

這是因為arr[i] += fullname + '\t' + email + '\t' + commitsnum;行上的+= = . 將其更改為=

在賦值之前, arr[i]是未定義的。 也許您混淆了按索引分配數組條目的語法,並附加到數組( arr.push(...) ),認為+=會推送,但事實並非如此。 它將新值附加到當前值。 並且由於該行是第一次為arr[i]分配任何內容,因此當前值未定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM