js 的几个方法记录一下

/* URL queryString
------------------------------------ */
function queryString (url, params) {
  // 没有 query 参数时,直接返回
  if (!params) { return url }

  // 有 query 参数
  let queryAry = [];
  Object.keys(params).map(v => {
    queryAry.push(`${v}=${params[v]}`)
  })
  return url + '?' + queryAry.join('&')
}

/* timestamp transform
------------------------------------ */
function timeTransform (timestamp, sign = '/') {
  // 无时间戳
  if (!timestamp) return

  // 有时间戳
  let date = new Date(timestamp);
  let yearObj = {
    year: date.getFullYear(),
    month: pad(date.getMonth() + 1, 2),
    day: pad(date.getDate(), 2),
  };
  let secondsObj = {
    hour: pad(date.getHours(), 2),
    minute: pad(date.getMinutes(), 2),
    seconds: pad(date.getSeconds(), 2)
  };

  return Object.values(yearObj).join(sign) + ' ' + Object.values(secondsObj).join(':')
}

/* 补全 0
------------------------------------- */
function pad(num, n) {
  var len = num.toString().length;
  while (len < n) {
    num = "0" + num;
    len++;
  }
  return num;
}

猜你喜欢

转载自www.cnblogs.com/biangz/p/9264294.html