【问题标题】:javascript - use a variable from another function javascript - 'today is not defined at Object'javascript - 使用另一个函数中的变量 javascript - '今天未在对象中定义'
【发布时间】:2022-01-23 06:11:42
【问题描述】:

我尝试获取今天的日期,以便在带有函数的 URL(连接)中使用它。但是,每次我尝试运行它时,我都会遇到同样的错误:今天没有在 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)

【问题讨论】:

  • 你今天实际上在哪里声明。因为在该代码中您没有声明它,这就是您需要 var、let 或 const 的原因
  • 使该函数返回today
  • 这能回答你的问题吗? How to access variable outside js function

标签: javascript scope


【解决方案1】:
      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)

【讨论】:

  • 你的超出范围,要么在函数外声明变量,要么让函数返回值,前者更好
【解决方案2】:

这可能是您想要做的。因为 today 变量的作用域是你应该 return 它的函数,然后在定义 fetchURL 时你可以调用你的函数来访问 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)

【讨论】:

  • 声明today时需要varletconst
  • 谢谢我错过了。
【解决方案3】:

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


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);

【讨论】:

  • 实际上这更容易且有效。谢谢
猜你喜欢
  • 1970-01-01
  • 2013-10-27
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-09
  • 2017-08-24
相关资源
最近更新 更多