3.js基础--Math

Math基础

专门用于封装数学计算所用的API或常量

Math不能new


Math的API

1.取整

1>上取整:Math.ceil(num); 只要小数点超过,就取下一个整数。(ceil天花板)

var num = 123.001;

Math.ceil(num); // 124

var num = 123.000;

Math.ceil(num);   //123

2>下取整:Math.floor(num);  舍弃小数部分  (floor 地板)

var num = 123.999

Math.floor(num); //123

Math.floor(num)  vs   parseInt(str);

1.两者都是舍弃小数部分,取整

2.Math.floor(num)只能 对纯数字下取整;parseInt(str)去掉末位的非数字下取整

var n = "123.321a";

parseInt(n);//123

Math.floor(n); //NaN

3>四舍五入取整:Math.round(num)

var num = 123.321;

Math.round(num); // 123

Math.round(num);    vs    n.toFixed(d)

1.Math.round(num)只能取整,不能设定小数位数

   n.toFixed(d)可以按任意小数位数四舍五入

2.Math.round()返回值是数字,可以直接参与数字运算

   n.toFixed(d)返回的是字符串,参与运算需要类型转换。

var n = 123.321;

Math.round(n); // 123

n.toFixed(2); // 123.32

typeof  n.toFixed(2) // string

type of n:查看n的数据类型

2.乘方和开平方

Math.pow(底数,幂);

2的三次方    Math.pow(2,3);   //8

Math.sqrt(num); 开平方

Math.sqrt(4) //2

3.最大值和最小值

1.Math.max(n);

Math.max(1,2,3,4); //4

2.Math.min(n);

Math.min(1,2,3,4); //1

max 和 min 不支持数组类型的参数,解决方案:

Math.max.apply( undefined/math/null , arr );   // 获取数组中的最大值

the first parameter , you pass to apply of any function,will be the this inside that function.but,max doesn't depend on the current context . so anything would in-place of math

4.随机数

Math.random();   0<=r<1

1.从min--max之间随机生成一个随机整数

parseInt ( Math.random()* (max - min + 1 ) + min);

2.从0-max之间生成一个随机数

parseInt(Math.random()*(max+1))

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • .写一个函数,返回从min到max之间的 随机整数,包括min不包括max function randomness...
    邢烽朔阅读 328评论 0 1
  • 第一章: JS简介 从当初简单的语言,变成了现在能够处理复杂计算和交互,拥有闭包、匿名函数, 甚至元编程等...
    LaBaby_阅读 1,703评论 0 6
  • 有人说过,很多弯路到最后都成了直路,所有的坑到最后也都成了坦途;所谓的直路和坦途并不是摆在眼前的,都是不断的的...
    老衲法号一眉道人阅读 1,377评论 0 4
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,774评论 0 33
  • js简介 Js是一种基于事件和对象驱动的解释性、松散性的语言。 一切皆对象 javascript 布兰登艾奇 ...
    塔库纳玛哈哈阅读 1,239评论 0 2