关于javascript:js平常用到的一些方法

2次阅读

共计 15260 个字符,预计需要花费 39 分钟才能阅读完成。

判断对象否为空

export const isEmpty = obj => {return Object.keys(obj).length === 0
}

浮点数取整

const x = 123.4545;
x >> 0; // 123
~~x; // 123
x | 0; // 123
Math.floor(x); // 123

留神:前三种办法只实用于 32 个位整数,对于正数的解决上和 Math.floor 是不同的。

Math.floor(-12.53); // -13
-12.53 | 0; // -12

生成 6 位数字验证码

// 办法一
('000000' + Math.floor(Math.random() *  999999)).slice(-6);

// 办法二
Math.random().toString().slice(-6);

// 办法三
Math.random().toFixed(6).slice(-6);

// 办法四
'' + Math.floor(Math.random() * 999999);

16 进制色彩代码生成

(function() {
  return '#'+('00000'+
    (Math.random()*0x1000000<<0).toString(16)).slice(-6);
})();

驼峰命名转下划线

'componentMapModelRegistry'.match(/^[a-z][a-z0-9]+|[A-Z][a-z0-9]*/g).join('_').toLowerCase(); // component_map_model_registry

url 查问参数转 json 格局

// ES6
const query = (search = '') => ((querystring ='') => (q => (querystring.split('&').forEach(item => (kv => kv[0] && (q[kv[0]] = kv[1]))(item.split('='))), q))({}))(search.split('?')[1]);

// 对应 ES5 实现
var query = function(search) {if (search === void 0) {search = '';}
  return (function(querystring) {if (querystring === void 0) {querystring = '';}
    return (function(q) {return (querystring.split('&').forEach(function(item) {return (function(kv) {return kv[0] && (q[kv[0]] = kv[1]);
        })(item.split('='));
      }), q);
    })({});
  })(search.split('?')[1]);
};

query('?key1=value1&key2=value2'); // es6.html:14 {key1: "value1", key2: "value2"}

获取 URL 参数

function getQueryString(key){var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if(r!=null){return  unescape(r[2]);
  }
  return null;
}

n 维数组开展成一维数组

var foo = [1, [2, 3], ['4', 5, ['6',7,[8]]], [9], 10];

// 办法一
// 限度:数组项不能呈现 `,`,同时数组项全副变成了字符数字
foo.toString().split(','); // ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

// 办法二
// 转换后数组项全副变成数字了
eval('[' + foo + ']'); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// 办法三,应用 ES6 开展操作符
// 写法太过麻烦,太过死板
[1, ...[2, 3], ...['4', 5, ...['6',7,...[8]]], ...[9], 10]; // [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]

// 办法四
JSON.parse(`[${JSON.stringify(foo).replace(/[|]/g, '')}]`); // [1, 2, 3,"4", 5,"6", 7, 8, 9, 10]

// 办法五
const flatten = (ary) => ary.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
flatten(foo); // [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]

// 办法六
function flatten(a) {return Array.isArray(a) ? [].concat(...a.map(flatten)) : a;
}
flatten(foo); // [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]

// 办法七
var flatten = function(arr) {var result = [];
  var flat = function* (a) {
    var length = a.length;
    for (var i = 0; i < length; i++) {var item = a[i];
      if (typeof item !== 'number') {yield * flat(item);
      } else {yield item;}
    }
  }

  for (var f of flat(arr)) {result.push(f);
  }

  return result;
}

注:更多办法请参考《How to flatten nested array in JavaScript?》

日期格式化

// 办法一
function format1(x, y) {
  var z = {y: x.getFullYear(),
    M: x.getMonth() + 1,
    d: x.getDate(),
    h: x.getHours(),
    m: x.getMinutes(),
    s: x.getSeconds()};
  return y.replace(/(y+|M+|d+|h+|m+|s+)/g, function(v) {return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-(v.length > 2 ? v.length : 2))
  });
}

format1(new Date(), 'yy-M-d h:m:s'); // 17-10-14 22:14:41

// 办法二
Date.prototype.format = function (fmt) { 
  var o = {"M+": this.getMonth() + 1, // 月份 
    "d+": this.getDate(), // 日 
    "h+": this.getHours(), // 小时 
    "m+": this.getMinutes(), // 分 
    "s+": this.getSeconds(), // 秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度 
    "S": this.getMilliseconds() // 毫秒};
  if (/(y+)/.test(fmt)){fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  } 
  for (var k in o){if (new RegExp("(" + k + ")").test(fmt)){fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }     
  return fmt;
}

new Date().format('yy-M-d h:m:s'); // 17-10-14 22:18:17

计算绝对工夫

/**
 * 计算绝对工夫
 * @param {number} stamp 工夫缀
 */
export const timeAgo = (stamp) => {
    const minute = 1000 * 60
    const hour = minute * 60
    const day = hour * 24
    const week = day * 7
    const month = day * 30
    const now = new Date().getTime()
    const difftime = now - stamp

    if (difftime < 0) return
    const minuteDiff = difftime / minute
    const hourDiff = difftime / hour
    const dayDiff = difftime / day
    const weekDiff = difftime / week
    const monthDiff = difftime / month

    if (monthDiff >= 1 && monthDiff < 3) {return `${parseInt(monthDiff)}月前 `
    } else if (weekDiff >= 1 && weekDiff < 4) {return `${parseInt(weekDiff)}周前 `
    } else if (dayDiff >= 1 && dayDiff < 6) {return `${parseInt(dayDiff)}天前 `
    } else if (hourDiff >= 1 && hourDiff < 24) {return `${parseInt(hourDiff)}小时前 `
    } else if (minuteDiff >= 1 && minuteDiff < 59) {return `${parseInt(minuteDiff)}分钟前 `
    } else if (difftime >= 0 && difftime <= minute) {return '刚刚'}
}

简略深拷贝

/**
 * 合乎 JSON 标准数据的深拷贝,日期格局要求为 `xxxx-xx-xx xx:xx:xx`
 * @param obj 数据源
 * @returns {any}
 */
export const clone = (obj) => {const regExp = /^d{4}-d{2}-d{2}Td{2}:d{2}d{2}.d{3}Z$/
    return JSON.parse(JSON.stringify(obj), function (k, v) {if (typeof v === 'string' && regExp.test(v)) {return new Date(v)
        }
        return v
    })
}

提早执行 Promise

/**
 * 异步提早执行
 * @param t 工夫毫秒数
 * @param v 执行函数
 * @returns {Promise<any>}
 */
export const delay = (t, v) => {return new Promise(function (resolve) {setTimeout(resolve.bind(null, v), t)
    })
}

统计文字个数

function wordCount(data) {var pattern = /[a-zA-Z0-9_u0392-u03c9]+|[u4E00-u9FFFu3400-u4dbfuf900-ufaffu3040-u309fuac00-ud7af]+/g;
  var m = data.match(pattern);
  var count = 0;
  if(m === null) return count;
  for (var i = 0; i < m.length; i++) {if (m[i].charCodeAt(0) >= 0x4E00) {count += m[i].length;
    } else {count += 1;}
  }
  return count;
}

var text = '贷款买房,也意味着你能给本人的资产加杠杆,可能撬动更多的钱,来孳生更多的财务性支出。';
wordCount(text); // 38

特殊字符本义

function htmlspecialchars (str) {var str = str.toString().replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g,'&quot;');
  return str;
}

htmlspecialchars('&jfkds<>'); // "&amp;jfkds&lt;&gt;"

动静插入 js

function injectScript(src) {
    var s, t;
    s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = src;
    t = document.getElementsByTagName('script')[0];
    t.parentNode.insertBefore(s, t);
}

格式化数量

// 办法一
function formatNum (num, n) {if (typeof num == "number") {num = String(num.toFixed(n || 0));
    var re = /(-?d+)(d{3})/;
    while (re.test(num)) num = num.replace(re, "$1,$2");
    return num;
  }
  return num;
}

formatNum(2313123, 3); // "2,313,123.000"

// 办法二
'2313123'.replace(/B(?=(d{3})+(?!d))/g, ','); // "2,313,123"

// 办法三
function formatNum(str) {return str.split('').reverse().reduce((prev, next, index) => {return ((index % 3) ? next : (next + ',')) + prev
  });
}

formatNum('2313323'); // "2,313,323"

身份证验证

function chechCHNCardId(sNo) {if (!this.regExpTest(sNo, /^[0-9]{17}[X0-9]$/)) {return false;}
  sNo = sNo.toString();

  var a, b, c;
  a = parseInt(sNo.substr(0, 1)) * 7 + parseInt(sNo.substr(1, 1)) * 9 + parseInt(sNo.substr(2, 1)) * 10;
  a = a + parseInt(sNo.substr(3, 1)) * 5 + parseInt(sNo.substr(4, 1)) * 8 + parseInt(sNo.substr(5, 1)) * 4;
  a = a + parseInt(sNo.substr(6, 1)) * 2 + parseInt(sNo.substr(7, 1)) * 1 + parseInt(sNo.substr(8, 1)) * 6;
  a = a + parseInt(sNo.substr(9, 1)) * 3 + parseInt(sNo.substr(10, 1)) * 7 + parseInt(sNo.substr(11, 1)) * 9;
  a = a + parseInt(sNo.substr(12, 1)) * 10 + parseInt(sNo.substr(13, 1)) * 5 + parseInt(sNo.substr(14, 1)) * 8;
  a = a + parseInt(sNo.substr(15, 1)) * 4 + parseInt(sNo.substr(16, 1)) * 2;
  b = a % 11;

  if (b == 2) {c = sNo.substr(17, 1).toUpperCase();} else {c = parseInt(sNo.substr(17, 1));
  }

  switch (b) {
    case 0:
      if (c != 1) {return false;}
      break;
    case 1:
      if (c != 0) {return false;}
      break;
    case 2:
      if (c != "X") {return false;}
      break;
    case 3:
      if (c != 9) {return false;}
      break;
    case 4:
      if (c != 8) {return false;}
      break;
    case 5:
      if (c != 7) {return false;}
      break;
    case 6:
      if (c != 6) {return false;}
      break;
    case 7:
      if (c != 5) {return false;}
      break;
    case 8:
      if (c != 4) {return false;}
      break;
    case 9:
      if (c != 3) {return false;}
      break;
    case 10:
      if (c != 2) {return false;};
  }
  return true;
}

测试质数

function isPrime(n) {return !(/^.?$|^(..+?)1+$/).test('1'.repeat(n))
}

统计字符串中雷同字符呈现的次数

var arr = 'abcdaabc';

var info = arr
    .split('')
    .reduce((p, k) => (p[k]++ || (p[k] = 1), p), {});

console.log(info); //{a: 3, b: 2, c: 2, d: 1}

应用 void 0 来解决 undefined 被净化问题

undefined = 1;
!!undefined; // true
!!void(0); // false

单行写一个评级组件

"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);

JavaScript 错误处理的形式的正确姿态

try {something} catch (e) {
    window.location.href =
        "http://stackoverflow.com/search?q=+" +
        e.message;
}

匿名函数自执行写法

(function() {}() );
(function() {})();
[function() {}() ];

~ function() {}();
! function() {}();
+ function() {}();
- function() {}();

delete function() {}();
typeof function() {}();
void function() {}();
new function() {}();
new function() {};

var f = function() {}();

1, function() {}();
1 ^ function() {}();
1 > function() {}();

两个整数替换数值

var a = 20, b = 30;
a ^= b;
b ^= a;
a ^= b;

a; // 30
b; // 20

数字字符转数字

var a = '1';
+a; // 1

最短的代码实现数组去重

[...new Set([1, "1", 2, 1, 1, 3])]; // [1, "1", 2, 3]

用最短的代码实现一个长度为 m(6)且值都 n(8)的数组

Array(6).fill(8); // [8, 8, 8, 8, 8, 8]

将 argruments 对象转换成数组

var argArray = Array.prototype.slice.call(arguments);

// ES6:var argArray = Array.from(arguments)

// or
var argArray = [...arguments];

获取日期工夫缀

// 获取指定工夫的工夫缀
new Date().getTime();
(new Date()).getTime();
(new Date).getTime();
// 获取以后的工夫缀
Date.now();
// 日期显示转换为数字
+new Date();

应用 ~x.indexOf('y') 来简化x.indexOf('y') > -1

var str = 'hello world';
if (str.indexOf('lo') > -1) {// ...}

if (~str.indexOf('lo')) {// ...}

parseInt() or Number()

两者的差异之处在于 解析 转换 两者之间的了解。

解析 容许 字符串中含有非数字字符,解析按从左到右的程序,如果遇到非数字字符就进行。而转换 不容许 呈现非数字字符,否者会失败并返回 NaN。

var a = '520';
var b = '520px';

Number(a); // 520
parseInt(a); // 520

Number(b); // NaN
parseInt(b); // 520

parseInt办法第二个参数用于指定转换的基数,ES5 默认为 10 进制。

parseInt('10', 2); // 2
parseInt('10', 8); // 8
parseInt('10', 10); // 10
parseInt('10', 16);  // 16

对于网上 parseInt(0.0000008) 的后果为什么为 8,起因在于 0.0000008 转换成字符为 ”8e-7″,而后依据 parseInt 的解析规定天然失去 ”8″ 这个后果。

+拼接操作,+x or String(x)

+ 运算符可用于数字加法,同时也能够用于字符串拼接。如果 + 的其中一个操作符是字符串(或者通过 隐式强制转换能够失去字符串),则执行字符串拼接;否者执行数字加法。

须要留神的时对于数组而言,不能通过 valueOf() 办法失去简略根本类型值,于是转而调用 toString() 办法。

[1,2] + [3, 4]; // "1,23,4"

对于对象同样会先调用 valueOf() 办法,而后通过 toString() 办法返回对象的字符串示意。

var a = {};
a + 123; // "[object Object]123"

对于 a + "" 隐式转换和 String(a) 显示转换有一个轻微的差异:a +''会对 a 调用 valueOf() 办法,而 String() 间接调用 toString() 办法。大多数状况下咱们不会思考这个问题,除非真遇到。

var a  = {valueOf: function() {return 42;},
  toString: function() { return 4;}
}

a + ''; // 42
String(a); // 4

判断对象的实例

// 办法一: ES3
function Person(name, age) {if (!(this instanceof Person)) {return new Person(name, age);
  }
  this.name = name;
  this.age = age;
}

// 办法二: ES5
function Person(name, age) {var self = this instanceof Person ? this : Object.create(Person.prototype);
  self.name = name;
  self.age = age;

  return self;
}

// 办法三:ES6
function Person(name, age) {if (!new.target) {throw 'Peron must called with new';}
  this.name = name;
  this.age = age;
}

数据安全类型查看

// 对象
function isObject(value) {return Object.prototype.toString.call(value).slice(8, -1) === 'Object'';
}

// 数组
function isArray(value) {return Object.prototype.toString.call(value).slice(8, -1) === 'Array';
}

// 函数
function isFunction(value) {return Object.prototype.toString.call(value).slice(8, -1) === 'Function';
}

让数字的字面值看起来像对象

2.toString(); // Uncaught SyntaxError: Invalid or unexpected token

2..toString(); // 第二个点号能够失常解析
2 .toString(); // 留神点号后面的空格
(2).toString(); // 2 先被计算

对象可计算属性名(仅在 ES6 中)

var suffix = 'name';
var person = {['first' + suffix]: 'Nicholas',
  ['last' + suffix]: 'Zakas'
}

person['first name']; // "Nicholas"
person['last name']; // "Zakas"

数字四舍五入

// v: 值,p: 精度
function (v, p) {p = Math.pow(10, p >>> 31 ? 0 : p | 0)
  v *= p;
  return (v + 0.5 + (v >> 31) | 0) / p
}

round(123.45353, 2); // 123.45

在浏览器中依据 url 下载文件

function download(url) {var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;

  if (isChrome || isSafari) {var link = document.createElement('a');
    link.href = url;

    if (link.download !== undefined) {var fileName = url.substring(url.lastIndexOf('/') + 1, url.length);
      link.download = fileName;
    }

    if (document.createEvent) {var e = document.createEvent('MouseEvents');
      e.initEvent('click', true, true);
      link.dispatchEvent(e);
      return true;
    }
  }

  if (url.indexOf('?') === -1) {url += '?download';}

  window.open(url, '_self');
  return true;
}

疾速生成 UUID

function uuid() {var d = new Date().getTime();
  var uuid = 'xxxxxxxxxxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
};

uuid(); // "33f7f26656cb-499b-b73e-89a921a59ba6"

JavaScript 浮点数精度问题

function isEqual(n1, n2, epsilon) {
  epsilon = epsilon == undefined ? 10 : epsilon; // 默认精度为 10
  return n1.toFixed(epsilon) === n2.toFixed(epsilon);
}

0.1 + 0.2; // 0.30000000000000004
isEqual(0.1 + 0.2, 0.3); // true

0.7 + 0.1 + 99.1 + 0.1; // 99.99999999999999
isEqual(0.7 + 0.1 + 99.1 + 0.1, 100); // true

格式化表单数据

function formatParam(obj) {
  var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

  for(name in obj) {value = obj[name];

    if(value instanceof Array) {for(i=0; i<value.length; ++i) {subValue = value[i];
        fullSubName = name + '[' + i + ']';
        innerObj = {};
        innerObj[fullSubName] = subValue;
        query += formatParam(innerObj) + '&';
      }
    }
    else if(value instanceof Object) {for(subName in value) {subValue = value[subName];
        fullSubName = name + '[' + subName + ']';
        innerObj = {};
        innerObj[fullSubName] = subValue;
        query += formatParam(innerObj) + '&';
      }
    }
    else if(value !== undefined && value !== null)
      query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
  }
  return query.length ? query.substr(0, query.length - 1) : query;
}

var param = {
  name: 'jenemy',
  likes: [0, 1, 3],
  memberCard: [{ title: '1', id: 1},
    {title: '2', id: 2}
  ]
}

formatParam(param); // "name=12&likes%5B0%5D=0&likes%5B1%5D=1&likes%5B2%5D=3&memberCard%5B0%5D%5Btitle%5D=1&memberCard%5B0%5D%5Bid%5D=1&memberCard%5B1%5D%5Btitle%5D=2&memberCard%5B1%5D%5Bid%5D=2"

创立指定长度非空数组

在 JavaScript 中能够通过 new Array(3) 的模式创立一个长度为 3 的空数组。在老的 Chrome 中其值为 [undefined x 3],在最新的 Chrome 中为[empty x 3],即空单元数组。在老 Chrome 中,相当于显示应用[undefined, undefined, undefined] 的形式创立长度为 3 的数组。

然而,两者在调用 map() 办法的后果是显著不同的

var a = new Array(3);
var b = [undefined, undefined, undefined];

a.map((v, i) => i); // [empty × 3]
b.map((v, i) => i); // [0, 1, 2]

少数状况咱们冀望创立的是蕴含 undefined 值的指定长度的空数组,能够通过上面这种办法来达到目标:

var a = Array.apply(null, { length: 3});

a; // [undefined, undefined, undefined]
a.map((v, i) => i); // [0, 1, 2]

总之,尽量不要创立和应用空单元数组。

debounce 办法

debounce()办法用来提早执行函数。

var debounce = function (func, threshold, execAsap) {
  var timeout;

  return function debounced() {
    var obj = this, args = arguments;
    function delayed() {if (!execAsap)
        func.apply(obj, args);
      timeout = null;
    };

    if (timeout)
      clearTimeout(timeout);
    else if (execAsap)
      func.apply(obj, args);

    timeout = setTimeout(delayed, threshold || 100);
  };
}

判断客户端

var browser = {v: (function() {
        var u = navigator.userAgent,
            app = navigator.appVersion,
            p = navigator.platform;
        return {trident: u.indexOf('Trident') > -1, //IE 内核
            presto: u.indexOf('Presto') > -1, //opera 内核
            webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, // 火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为挪动终端
            ios: !!u.match(/i[^;]+;(U;)? CPU.+Mac OS X/), //ios 终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android 终端或 uc 浏览器
            iPhone: u.indexOf('iPhone') > -1, // 是否为 iPhone 或者 QQHD 浏览器
            iPad: u.indexOf('iPad') > -1, // 是否 iPad
            weixin: u.indexOf('MicroMessenger') > -1, // 是否微信
            webApp: u.indexOf('Safari') == -1, // 是否 web 应该程序,没有头部与底部
            UCB: u.match(/UCBrowser/i) == "UCBrowser",
            QQB: u.match(/MQQBrowser/i) == "MQQBrowser",
            win: p.indexOf('Win') > -1, // 判断是否是 WIN 操作系统
            mac: p.indexOf('Mac') > -1 // 判断是否是 Mac 操作系统
        };
    })()}

计算输出字符数并且辨别中英文

英文、数字包含英文符号占一个长度,中文和中文标点符号占二个长度,这里也只解决常见的中文符号。

// 判断是否为中文
export const isChinese = ch => {const HAN_REGEX = /[u2E80-u2E99u2E9B-u2EF3u2F00-u2FD5u3005u3007u3021-u3029u3038-u303Bu3400-u4DB5u4E00-u9FD5uF900-uFA6DuFA70-uFAD9]/;
  return !!ch.match(HAN_REGEX);
};

// 判断是否为常见中文符号
export const isChinesePunctuation = ch => {
  // 中文标点符号 ·!¥……()——【】?、,。《》;:‘’“”「」const HAN_PUNCTUATION_REGEX = /[u0026u0023u0031u0038u0033u003buff01uffe5u2026u2026uff08uff09u2014u2014u3010u3011uff1fu3001uff0cu3002u300au300buff1buff1au2018u2019u201cu201du300cu300d]/;
  return !!ch.match(HAN_PUNCTUATION_REGEX);
};

// 判断是否英文字母,蕴含数字
export const isEnglish = ch => {const code = ch.codePointAt(0);
  return (code > 64 && code < 91) || (code > 96 && code < 123) || (code > 48 && code < 58);
}

// 统计字符串的长度,中文占二个字节,英文占一个字节
export const getChCount = str => {const trimmedStr = str.trim();
  let count = 0;

  for (let i = 0; i < trimmedStr.length; i++) {
    // 先判断英文,实测发现中文符号在编码上解析进去的有可能和英文一样,导致统计谬误
    if (isEnglish(trimmedStr[i])) {count += 1;} else if (isChinese(trimmedStr[i]) || isChinesePunctuation(trimmedStr[i])) {count += 2;} else {count += 1;}
  }

  return count;
}

留神:下面并没有残缺的测试,应用时请多测试一下,及时反馈。

依据字节显示大小

/**
 * 解析字节,例如:* 1000000 bytes -> {size: 976.6, unit: 'kB'}
 *
 * @param bytes 字节大小
 * @returns {{size: number, unit: (string|string|string|string|string|string|string|string)}}
 */
export const parseBytes = (bytes: number): {size: number, unit: string} => {
  let i = -1;
  const byteUnits = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  do {
    bytes = bytes / 1024;
    i++;
  } while (bytes > 1024);

  return {size: parseFloat(Math.max(bytes, 0.1).toFixed(1)),
    unit: byteUnits[i]
  };
};

将字符串解析成 DOM

var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>"
  , parser = new DOMParser()
  , doc = parser.parseFromString(xmlString, "text/xml");
doc.firstChild // => <div id="foo">...
doc.firstChild.firstChild // => <a href="#">...
正文完
 0