请解释这个Javascript教程

mjm*_*che 1 javascript

我是个新手,我对这个教程感到困惑.我知道(至少我认为我知道)函数getDate和get Month以及getFullYear是由JavaScript确定的预设函数.

如果将新日期(2000,0,1)作为formatDate的参数提交,为什么本教程需要这些预设函数?getDate会以某种方式与作为参数提交的数字发生冲突吗?

在函数键盘中,我理解"数字"检查数字是否小于10,如果是,则添加零,但提交给功能键的参数是什么?如何检查数字?

你可以一步一步地带我(使用简单的语言)这个教程...提前谢谢你

function formatDate(date) {
  function pad(number) {
    if (number < 10)
      return "0" + number;
    else
      return number;
  }
  return pad(date.getDate()) + "/" + pad(date.getMonth() + 1) +
             "/" + date.getFullYear();
}
print(formatDate(new Date(2000, 0, 1)));
Run Code Online (Sandbox Code Playgroud)

eap*_*pen 6

此功能格式化并打印日期.

pad函数是在小于10的数字前添加"0"(不是如你所说的那样加10).

这允许您以dd/mm/yyyy格式打印日期.例如.2011年2月3日将打印为03/02/2011而不是2011年3月2日

在formatDate函数中,最后一行是返回键盘(...."formatDate"函数中的"pad"函数获取每个日期部分并将其发送到填充函数以预先设置"0"以确保mm/dd遵循而不是发送单个数字变量 - 例如3/2/2011

function formatDate(date) { // date is passed here
  function pad(number) {    // note that this function is defined within the outer function
    if (number < 10)
      return "0" + number; // prepend a 0 if number is less than 10
    else
      return number; // if number is greater than 10, no prepending necessary
  }  // the pad function ends here 
  return pad(date.getDate()) + "/" + pad(date.getMonth() + 1) +
             "/" + date.getFullYear(); // note how the pad is used around the "date" and "month" only 
} // the formatDate function ends here
print(formatDate(new Date(2000, 0, 1)));
Run Code Online (Sandbox Code Playgroud)

希望有助于澄清事情.

这一行:

 return pad(date.getDate()) + "/" + pad(date.getMonth() + 1) +
                 "/" + date.getFullYear();
Run Code Online (Sandbox Code Playgroud)

转换为(假设日期为23/2/2011)

 return pad(23) + "/" + pad(1 + 1) +  "/" + 2011;
Run Code Online (Sandbox Code Playgroud)

这调用pad(23) - 并且23被替换为pad函数中的"number"变量.无需更改,返回23.

pad(1 + 1)= pad(2) - 和2被替换为pad函数中的"number"变量.它附加一个"0"并返回"02"

所以,最后的转换是

return 23 + "/" + 02 + "/" + 2011;
Run Code Online (Sandbox Code Playgroud)

它最终打印"23/02/2011".