JavaScript Math 函数

Math常用的方法

函数 说明
abs(x) 返回数的绝对值
ceil(x) 对数进行上舍入
floor(x) 对数进行下舍入
max(x,y) 返回 x 和 y 中的最高值
min(x,y) 返回 x 和 y 中的最低值
pow(x,y) 返回 x 的 y 次幂
random() 返回 0 ~ 1 之间的随机数
round(x) 把数四舍五入为最接近的整数
console.log(Math.abs(-6));//6
console.log(Math.pow(3,4));// 3的4次方

console.log(Math.ceil(10.9)); // 向上取整 11
console.log(Math.ceil(10.1)); // 11
console.log(Math.ceil(-10.1));// -10
console.log(Math.ceil(-10.9));// -10

console.log(Math.floor(10.9)); // 向下取整 10
console.log(Math.floor(10.1)); // 10
console.log(Math.floor(-10.1));// -11
console.log(Math.floor(-10.9));// -11

console.log(Math.round(10.9));
console.log(Math.round(-10.9));

console.log(Math.max(10,4,100,-2,11));
练习
//0-1的随机数
for (var i = 0; i < 100; i++) {
     console.log(Math.random());
}

// [0,1]
console.log(Math.round(Math.random()));

//0-10的随机数
for (var i = 0; i < 100; i++) {
     console.log(Math.round(Math.random() * 10));
}

//5-10的随机数
console.log(Math.round(Math.random()*5+5));
max的源码实现
<script>
    function MyMax() {
        this.getMax = function() {
            var max = arguments[0];
            for (var i = 0; i < arguments.length; i++) {
                if (max < arguments[i]) {
                    max = arguments[i];
                }
            }
            return max
        }
    }
    var vm = new MyMax();
    var resulst = vm.getMax(11, 22, 3311, 33, 55)
    document.write(resulst)
</script>
随机生成一个颜色

v1.0

// 产生一个随机颜色
// #a36633  0~f
function getColor() {
    var str = '0123456789abcdef'; // 0-15
    var color = "# ";
    // 循环6次 每次随机生成一个字符
    for (var i = 0; i < 6; i++) {
        var num = rand(0, 15);
        //color += str.charAt(num);
        color += str[num];
    }
    return color;
}
console.log(getColor());

v2.0

<style>
div {
  width: 300px;
  height: 200px;
  background-color: pink;
}
</style>

</head>
<body>
<div id="dv"></div>
<script>
//随机产生一个十六进制的颜色值
//封装成一个函数
console.log(parseInt(Math.random() * 5));

function getColor() {
  var str = "#";
  //一个十六进制的值的数组
  var arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
  for (var i = 0; i < 6; i++) {
	//产生的每个随机数都是一个索引,根据索引找到数组中对应的值,拼接到一起
	var num = parseInt(Math.random() * 16);
	str += arr[num];
  }
  return str;
}
//页面记载的事件
window.onload = function () {
  //在文档中通过id属性的值查找这个元素(标签).设置该标签的背景颜色
  document.getElementById("dv").style.backgroundColor = getColor();
};
//console.log(getColor());
</script>




posted @ 2020-11-11 16:59  qqaazzhf  阅读(86)  评论(0)    收藏  举报