当前位置:   article > 正文

js--引用类型单体内置对象--Math,随机数生成_使用内置对象系统生成随机数

使用内置对象系统生成随机数

内置对象:
在所有代码执行之前,作用域中就可以存在两个内置对象:Global和Math。
这些对象在ECMAScript执行之前就已经纯在了,开发者不用显示的实例化内置对象。

1.Math对象

1.Math对象的属性

Math.E
Math.LN2
Math.LOG2E
Math.PI等

2.Math对象的方法
2.1min()和max()
alert(Math.max(3,54,32));//54
alert(Math.min(3,54,32));//3
  • 1
  • 2
2.2舍入方法

Math.ceil()向上舍入为最接近的整数
Math.floor()向下舍入为最接近的整数
Math.round()四舍五入

alert(Math.ceil(25.9));//26
alert(Math.ceil(25.1));//26
alert(Math.floor(25.9));//25
alert(Math.floor(25.1));//25
alert(Math.round(25.9));//26
alert(Math.round(25.1));//25
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
2.3random()方法

Math.random()是返回大于等于0小于1的一个随机数

//某个范围内随机选择一个整数值
值 = Math.floor(Math.random()*可能值的总数 + 第一个可能的值);
  • 1
  • 2
//eg:想选择1-10的值
var num = Math.floor(Math.random()*10 + 1);
  • 1
  • 2
//generate a random array between 10-100
var array = [];
for(var i = 0;i < 60;i++){
    array[i] = Math.floor(Math.random() * 91 + 10);
}
  • 1
  • 2
  • 3
  • 4
  • 5
//随机选择数组中的元素
function makePhrase {
    var word1 = ["ase","ewr","iuoh","zxc","ou"];
    var word2 = ["cvbw","ar","icxv","erxc","opsdf];
    var word3 = ["bv","eer","iua","zkyh","af"];
    //随机生成的一个短语
    var rand1 = Math.floor(Math.random()*word1.length);
    var rand2 = Math.floor(Math.random()*word2.length);
    var rand3 = Math.floor(Math.random()*word2.length);
    var phrase = word1[rand1]+" "+word2[rand2]+" "+word3[rand3];
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
2.4其他方法

Math.tan(x)
Math.cos(x)
Math.aqrt(x)等

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/54569
推荐阅读
相关标签
  

闽ICP备14008679号