ES6开发技巧:Number Skill数值技巧

2019-08-2819:13:13WEB前端开发Comments1,877 views字数 904阅读模式

Number Skill

取整

代替正数的Math.floor(),代替负数的Math.ceil()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/15860.html

const num1 = ~~ 1.69;
const num2 = 1.69 | 0;
const num3 = 1.69 >> 0;
// num1 num2 num3 => 1 1 1
复制代码
补零
const FillZero = (num, len) => num.toString().padStart(len, "0");
const num = FillZero(169, 5);
// num => "00169"
复制代码
转数值

只对null、""、false、数值字符串有效文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/15860.html

const num1 = +null;
const num2 = +"";
const num3 = +false;
const num4 = +"169";
// num1 num2 num3 num4 => 0 0 0 169
复制代码
时间戳
const timestamp = +new Date("2019-02-14");
// timestamp => 1550102400000
复制代码
精确小数
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
const num = RoundNum(1.69, 1);
// num => 1.7
复制代码
判断奇偶
const OddEven = num => !!(num & 1) ? "odd" : "even";
const num = OddEven(2);
// num => "even"
复制代码
取最小最大值
const arr = [0, 1, 2];
const min = Math.min(...arr);
const max = Math.max(...arr);
// min max => 0 2
复制代码
生成范围随机数
const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const num = RandomNum(1, 10);

作者:JowayYoung
链接:https://juejin.im/post/5cc7afdde51d456e671c7e48
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/15860.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/15860.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/15860.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定