最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
JavaScript前端开发时数值运算技巧代码示例
时间:2020-07-28 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下JavaScript前端开发时数值运算技巧代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
1.格式化金钱值
const ThousandNum = num => num.toString().replace(/B(?=(d{3})+(?!d))/g, ","); const money = ThousandNum(20190214); // money => "20,190,214"
2.取整代替正数的Math.floor(),代替负数的Math.ceil()
const num1 = ~~ 1.69; const num2 = 1.69 | 0; const num3 = 1.69 >> 0; // num1 num2 num3 => 1 1 1
3.转数值只对null、""、false、数值字符串有效
const num1 = +null; const num2 = +""; const num3 = +false; const num4 = +"169"; // num1 num2 num3 num4 => 0 0 0 169
4.精确小数
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal; const num = RoundNum(1.69, 1); // num => 1.7
5.取最小最大值
const arr = [0, 1, 2]; const min = Math.min(...arr); const max = Math.max(...arr); // min max => 0 2
6.是否为空对象
const obj = {}; const flag = DataType(obj, "object") && !Object.keys(obj).length; // flag => true
7.判断数据类型
function DataType(tgt, type) { const dataType = Object.prototype.toString.call(tgt).replace(/[object (w+)]/, "$1").toLowerCase(); return type ? dataType === type : dataType; } DataType("liner"); // "string" DataType(2020630); // "number" DataType(true); // "boolean" DataType([], "array"); // true DataType({}, "array"); // false
8.克隆数组
const _arr = [0, 1, 2]; const arr = [..._arr]; // arr => [0, 1, 2]
9.合并数组
const arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; const arr = [...arr1, ...arr2]; // arr => [0, 1, 2, 3, 4, 5];
10.去重数组
const arr = [...new Set([0, 1, 1, null, null])]; // arr => [0, 1, null]
11.截断数组
const arr = [...new Set([0, 1, 1, null, null])]; // arr => [0, 1, null]
12.交换赋值
let a = 0; let b = 1; [a, b] = [b, a]; // a b => 1 0
13.克隆对象
const _obj = { a: 0, b: 1, c: 2 }; // 以下方法任选一种(本人偏爱第一种,简单明了,与克隆数组几乎一样) const obj = { ..._obj }; const obj = JSON.parse(JSON.stringify(_obj)); // obj => { a: 0, b: 1, c: 2 }
14.合并对象
const obj1 = { a: 0, b: 1, c: 2 }; const obj2 = { c: 3, d: 4, e: 5 }; const obj = { ...obj1, ...obj2 }; // obj => { a: 0, b: 1, c: 3, d: 4, e: 5 }
为什么 obj 不是 {a:0,b:1,c:2,d:4,e:5}而是上面结果 下面相同的例子就可以说明
相关文章
- SpringBoot测试配置属性与web启动环境解析 10-24
- SpringBoot常用计量与bean属性校验和进制数据转换规则解析 10-24
- 工厂方法在Spring框架中的运用介绍 10-24
- SpringBoot热部署设置详解 10-24
- JavaScript二叉搜索树构建操作解析 10-12
- JavaScript二叉树及各种遍历算法讲解 10-12