Why does the number add''to become a string type?

(date.getFullYear () +"") Why does the number add""to make it a string type you can use substr

export function formatDate(date, fmt) {
   if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
   }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
}
 
function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}
Jun.14,2022

the number is added to the string, and the number is converted into a string and then added to the string


in js, the + sign can be used not only as an operator for numeric operations, but also as a connector for string concatenation. Date.getFullYear () +''is equivalent to date.getFullYear () plus an empty string, so it acts as a connector. It is natural for date.getFullYear () +''to get the string type, which is usually used for implicit conversion from digital to string form.


for example, if the value of getFullYear here is 2019, then it is 2019 +. If a number and a string are added, the number will be converted to a string type first, that is, '2019 characters. The result is naturally' 2019 characters. You can check MDN for type conversion.

Menu