如何将变量作为字符串传递以定位要由 d3 读取的文件

How to pass a variable as a string to locate a file to be read by d3

我希望我的代码查看日期,将其分配为变量,并将变量值作为适当文件位置的名称传递

我比较新。我发布的代码是我当前的语法尝试。

我意识到我的函数没有足够的参数。仍在努力掌握这一切。感谢您的帮助。

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Oct", "Nov", "Dec"]; 

var date = new Date();

d3.tsv("/Data/BlueForce1/`${date.getYear()}`/`${months[date.getMonth()]}`/2019.05.12.PT.txt);

到目前为止你有什么...

"/Data/BlueForce1/`${date.getYear()}`/`${months[date.getMonth()]}`/2019.05.12.PT.txt

... 是字符串与模板文字的奇怪组合,它甚至无效(您忘记了结束引号)。

你可以做两件事:

  1. 连接字符串:

这是最简单的选择,只需连接您的字符串:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Oct", "Nov", "Dec"];

var date = new Date();

var url = "/Data/BlueForce1/" + date.getYear() + "/" + months[date.getMonth()] + "/2019.05.12.PT.txt";

console.log(url)

  1. 模板文字

要使用模板文字,请使用反引号打开和关闭所有内容:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Oct", "Nov", "Dec"];

var date = new Date();

var url = `/Data/BlueForce1/${date.getYear()}/${months[date.getMonth()]}/2019.05.12.PT.txt`;

console.log(url)