常用的一些方法备份

96 阅读1分钟

toFixed方法重写 弃用四舍六入的银行家计算方式 改为四舍五入规则

export default function (m) { const number = this; if (typeof number !== 'number') { throw new Error("number不是数字"); } let result = Math.round(Math.pow(10, m) * number) / Math.pow(10, m); result = String(result); if (result.indexOf(".") == -1) { if (m != 0) { result += "."; result += new Array(m + 1).join('0'); } } else { let arr = result.split('.'); if (arr[1].length < m) { arr[1] += new Array(m - arr[1].length + 1).join('0') } result = arr.join('.') } return result };

获取树形集合

const nest = (items, id = null, link = 'parent_id') =>     items         .filter(item => item[link] === id)         .map(item => ({ ...item, children: nest(items, item.id) })); const comments = [   { id: 1, parent_id: null },   { id: 2, parent_id: 1 },   { id: 3, parent_id: 1 },   { id: 4, parent_id: 2 },   { id: 5, parent_id: 4 } ]; const nestedComments = nest(comments); console.log(nestedComments);

递归扁平化数组(多维数组)

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]

浮点数金额计算方法

//加法 Number.prototype.add = function(arg){ var r1,r2,m; try{r1=this.toString().split(".")[1].length}catch(e){r1=0} try{r2=arg.toString().split(".")[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)) return (this*m+arg*m)/m } //减法 Number.prototype.sub = function (arg){ return this.add(-arg); } //乘法 Number.prototype.mul = function (arg) { var m=0,s1=this.toString(),s2=arg.toString(); try{m+=s1.split(".")[1].length}catch(e){} try{m+=s2.split(".")[1].length}catch(e){} return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) } //除法 Number.prototype.div = function (arg){ var t1=0,t2=0,r1,r2; try{t1=this.toString().split(".")[1].length}catch(e){} try{t2=arg.toString().split(".")[1].length}catch(e){} with(Math){ r1=Number(this.toString().replace(".","")) r2=Number(arg.toString().replace(".","")) return (r1/r2)*pow(10,t2-t1); } }

js hashMap

`function HashMap() { this.map = {}; } HashMap.prototype = { put: function (key, value) {// 向Map中增加元素(key, value) this.map[key] = value; }, get: function (key) { //获取指定Key的元素值Value,失败返回Null if (this.map.hasOwnProperty(key)) { return this.map[key]; } return null; }, remove: function (key) { // 删除指定Key的元素,成功返回True,失败返回False if (this.map.hasOwnProperty(key)) { return delete this.map[key]; } return false; }, removeAll: function () { //清空HashMap所有元素 this.map = {}; }, keySet: function () { //获取Map中所有KEY的数组(Array) var _keys = []; for (var i in this.map) { _keys.push(i); } return _keys; }, toList() { return Object.values(this.map) || []; } }; HashMap.prototype.constructor = HashMap;

export default HashMap;`