likes
comments
collection
share

5 个 NICE 的 JavaScript 代码片段分享

作者站长头像
站长
· 阅读数 493

减轻阅读负担,启发创作心智,轻松学习 JavaScript 技巧,日拱一卒,jym,冲~

5 个 NICE 的 JavaScript 代码片段分享


4 种 html string 转 dom 方式

我们最常常用到 document.createElement('div') 然后用 div.innerHTML 赋值可以将 html string 转成 dom;除此之外,还可以通过另外 3 种方式实现同样效果,代码如下:

收藏等于学会~

// 方式 1
function str2DOMFn1(str) {
  const div = document.createElement('div');
  div.innerHTML = str;
  return div.firstElementChild;
}

// 方式 2
function str2DOMFn2(str) {
  return new DOMParser().parseFromString(str, 'text/html').body
    .firstElementChild;
}

// 方式 3
function str2DOMFn3(str) {
  return document.createRange().createContextualFragment(str);
}

// 方式 4
function str2DOMFn4(str) {
  const div = document.createElement('div');
  div.insertAdjacentHTML('afterbegin', str);
  return div.firstElementChild;
}

// test
function main(name) {
  const str = `<h1>Hello ${name}</h1>`;
  const element1 = str2DOMFn1(str) 
  const element2 = str2DOMFn2(str) 
  const element3 = str2DOMFn3(str) 
  const element4 = str2DOMFn4(str) 
  document.body.appendChild(element1);
  document.body.appendChild(element2);
  document.body.appendChild(element3);
  document.body.appendChild(element4);
}

main('World');
  • 在线地址:

5 个 NICE 的 JavaScript 代码片段分享

https://code.juejin.cn/pen/7133423354757218311

js 计算比特

我们常常需要计算比特大小,如何换算1024 是多少比特,可以用以下方法:

const formatBytes = (bytes, decimals = 2) => {
  if (bytes < 0) return '';
  if (bytes <= 1) return `${bytes}B`;
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / k ** i).toFixed(dm))}${sizes[i]}`;
};

// 🎉 1KB
console.log(formatBytes(1024));

// 🎉 1MB
console.log(formatBytes(1024 ** 2));
  • 在线地址:

https://code.juejin.cn/pen/7133465003029430309

4 种 js 格式化金钱方式

格式化金钱,我们提过很多次,这里提供 4 种方式进行格式化:

之前看有人问:为什么钱的格式要按千分位去划分?

原因是:依西方的习惯,每隔三位数加进一个逗号,也就是千位分隔符,以便更加容易认出数值。英语里没有“万”“亿”,只有“百万(million)”“十亿(billion)”,千位分隔符就是这么产生的。。。简而言之,“国际标准”~

// Option 1
function formatMoneyFn1(num) {
  return num.toLocaleString();
}

// Option 2
function formatMoneyFn2(num) {
  const nf = new Intl.NumberFormat();
  return nf.format(num);
}

// Option 3
function formatMoneyFn3(num) {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// Option 4
function formatMoneyFn4(num) {
  const arr = num.toString().split('');
  let index = -3;
  while (arr.length + index > 0) {
    arr.splice(index, 0, ',');
    index -= 4;
  }
  return arr.join('');
}

// 🎉 '20,220,316'
console.log(formatMoneyFn1(20220316));
console.log(formatMoneyFn2(20220316));
console.log(formatMoneyFn3(20220316));
console.log(formatMoneyFn4(20220316));
  • 在线地址:

https://code.juejin.cn/pen/7133465433373409311

解析 url 参数为对象

解析 url 参数,并生成对象,也是我们常常遇到的需求:

好用~

const getURLParams = (url) => {
  return (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce((acc, cur) => {
    const [k, v] = cur.split('=');
    const p = acc[k];

    acc[k] = p ? (Array.isArray(p) ? p : [p]).concat(v) : v;
    return acc;
  }, {});
};

// 🎉 {}
console.log(getURLParams('google.com'));

// 🎉 { name: '1', age: '2' }
console.log(getURLParams('https://www.google.com/?name=1&age=2'));

// Support duplicate key
// 🎉 { name: '1', age: [ '2', '3' ] }
console.log(getURLParams('https://www.google.com/?name=1&age=2&age=3'));

// 🎉 { name: '1', age: '2' }
console.log(getURLParams('name=1&age=2'));
  • 在线地址:

https://code.juejin.cn/pen/7133467809840889863

完全体深拷贝

什么样的深拷贝堪称完全体?即:任何类型的数据都会被深拷贝~ 看代码:

const deepClone = (obj, map = new WeakMap()) => {
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof RegExp) return new RegExp(obj);

  if (map.has(obj)) {
    return map.get(obj);
  }

  const allDesc = Object.getOwnPropertyDescriptors(obj);
  const cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);

  map.set(obj, cloneObj);

  for (const key of Reflect.ownKeys(obj)) {
    const value = obj[key];

    cloneObj[key] =
      value instanceof Object && typeof value !== 'function'
        ? deepClone(value, map)
        : value;
  }
  return cloneObj;
};
  • 在线地址:

https://code.juejin.cn/pen/7133468103555416094