三行代码  ›  专栏  ›  技术社区  ›  James

在数组上循环并在Javascript/Nodejs中输出模板字符串/文本

  •  0
  • James  · 技术社区  · 5 天前

    console.log 在nodejs终端中。

    我编写了以下代码来创建我的数组:

    // Get LTLAs from file
    var fs = require("fs");
    var text = fs.readFileSync("./LTLAs.txt", 'utf8');
    var LTLAs = text.split("\n");
    

    'Barking and Dagenham\r'
    'Babergh\r'
    'Aylesbury Vale\r'
    'Ashford\r'
    'Ashfield\r'
    'Arun\r'
    'Amber Valley\r'
    'Allerdale\r'
    'Adur\r'
    

    然后我在这个数组上循环:

    for (let i = 0; i < LTLAs.length; i++)
    {
        const endpoint = `https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=ltla;areaName=${LTLAs[i]}&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}`;
        console.log(endpoint);
    }
    

    我希望这会给我一组整洁的字符串,唯一的区别是 areaName=${LTLAs[i]}

    &structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}Dagenham
    &structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
    &structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}le
    &structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
    &structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
    &structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
    &structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
    &structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
    https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=ltla;areaName=Adur&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
    

    如果您能帮助所有字符串遵循与最终字符串相同的模式,我们将不胜感激。

    1 回复  |  直到 5 天前
        1
  •  2
  •   Mr. Hedgehog    5 天前

    您需要从字符串中删除回车符('\r')才能在节点js中获得正确的输出(某些浏览器可能会忽略它)。

    您可以在数组上迭代:

    var LTLAs = text.split("\n").map(string => string.replace('\r', ''));
    

    \r\n 而不是 \n

    var LTLAs = text.split("\r\n")