繁体   English   中英

javascript - 使用来自另一个 function javascript 的变量 - “今天未在对象中定义”

[英]javascript - use a variable from another function javascript - 'today is not defined at Object'

我尝试获取今天的日期以在 URL(串联)和 function 中使用它。 但是,每次我尝试运行它时,我都会遇到同样的错误:今天没有在 Object 定义

我尝试使用和不使用 var/let/const 来声明它,但错误仍然存在。 有人有想法吗(console.log())只是为了测试)?

 function GetTDDate() { today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); var yyyy = today.getFullYear(); today = yyyy + '-' + mm + '-' + dd; console.log(today); } const FetchURL = "https://static.data.gouv.fr/resources/donnees-relatives-aux-personnes-vaccinees-contre-la-covid-19-1/20211221-212503/vacsi-tot-fra-" + today + "-21h25.json" console.log(FetchURL)

这可能是您想要做的。 因为 today 变量的范围为 function 您应该return它,然后在定义fetchURL时,您可以调用 function 来访问today变量。

以下是您将如何执行此操作:

 function GetTDDate() { let today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); var yyyy = today.getFullYear(); today = yyyy + '-' + mm + '-' + dd; console.log(today); return today } const FetchURL = "https://static.data.gouv.fr/resources/donnees-relatives-aux-personnes-vaccinees-contre-la-covid-19-1/20211221-212503/vacsi-tot-fra-" + GetTDDate() + "-21h25.json" console.log(FetchURL)

      var today = new Date();


      function GetTDDate() {
      var dd = String(today.getDate()).padStart(2, '0');
      var mm = String(today.getMonth() + 1).padStart(2, '0');
      var yyyy = today.getFullYear();

       today = yyyy + '-' + mm + '-' + dd;
       console.log(today);

    const FetchURL = "https://static.data.gouv.fr/resources/donnees-relatives- 
   aux-personnes-vaccinees-contre-la-covid-19-1/20211221-212503/vacsi-tot-fra-" 
    + today + "-21h25.json"
     console.log(FetchURL)

请记得today申报,并在 function 中退回。

function GetTDDate() {
//do not forget to declare today
  const today = new Date();
  var dd = String(today.getDate()).padStart(2, '0');
  var mm = String(today.getMonth() + 1).padStart(2, '0');
  var yyyy = today.getFullYear();

  today = yyyy + '-' + mm + '-' + dd;
  console.log(today);
// Return the result
  return today

}
const FetchURL = "https://static.data.gouv.fr/resources/donnees-relatives-aux-personnes-vaccinees-contre-la-covid-19-1/20211221-212503/vacsi-tot-fra-" + GetTDDate() + "-21h25.json"

解决您的问题的一个更简单的方法是:


const FetchURL = `https://static.data.gouv.fr/resources/donnees-relatives-aux-personnes-vaccinees-contre-la-covid-19-1/20211221-212503/vacsi-tot-fra-${(new Date()).toISOString().slice(0,10)}-21h25.json`;

console.log(FetchURL);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM