目录
数学对象Math
参考:https://www.runoob.com/jsref/jsref-obj-math.html
https://www.runoob.com/js/js-obj-math.html
Math之对象的属性(基本常量)
Math之方法(取最大, 最小值)
console.log(Math.max(1,2,-5,8,666)); // 最大值
console.log(Math.min(1,2,-5,8,666)); // 最小值
Math之方法(取整)
将小数值舍入为整数的几个方法:Math.ceil()、Math.floor()和Math.round()。 这三个方法分别遵循下列舍入规则:
- Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;
- Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;
- Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数;
console.log(Math.ceil(2.45)); // 向上取整
console.log(Math.floor(2.45)); // 向下取整
console.log(Math.round(2.45)); // 四舍五入
Math之方法(取随机数)
Math.random()方法返回大于等于0 小于1 的一个随机数
console.log(Math.random()); // 随机数
实现两个数之间随机数
// // 获取两个数之间的随机数
// function rand(min,max) {
// return Math.random()*(max-min)+min; // 返回两个数之间的随机数,这里返回的结果是小数
// }
// for (var i=0;i<10;i++){
// console.log(Math.round(rand(3,10))); // 实现最大最小值之间的随机取整(通过对返回的随机小数四舍五入),循环得到
// }
// 改进后的代码,得到两个数之间的随机整数
function rand(min,max) {
return Math.round(Math.random()*(max-min)+min);
}
console.log(rand(3,11));
数学对象Math之方法(其他方法)
定时器与延时器
参考:https://blog.csdn.net/JBY2020/article/details/110149966
定时器与延时器的参数:
第一个参数是延时器要执行的代码函数
第二个参数是延时时间,即等待多长时间之后开始执行函数
延时器 setTimeout()
setTimeout(function(){},t):在 t 毫秒之后执行函数 function(){};
定时器setInterval()
setInterval(function(){},t):每隔 t 毫秒执行一次函数 function(){};
清除定时器clearInterval():定时器一旦开启就停不下来,所以需要使用延时器来清除定时器让其在指定时间后结束执行。括号中的参数为定时器对象
<script>
// 延时器
setTimeout(function() {
console.log('延时器执行');
}, 3000);
// 定时器
var st = setInterval(function(){
document.write('<p style="color: red;">你好!!!</p>');
},500);
// 清除定时器
setTimeout(() => {
clearInterval(st); // 定时器一旦开启就停不下来,所以需要使用延时器来清除定时器让其在指定时间后结束执行
}, 5000);
</script>
this的指向
重定向this对象:call()、apply()、bind() 方法
this指向被调用对象
箭头函数不能被call()、apply()、bind() 修改指向
定时器和延时器不能被call()、apply()、bind() 修改指向
<body>
<button>点击</button>
<script>
function fu1() {
this.name = '呵呵';
console.log(this);
}
console.log(window.name);
window.fu1(); // 普通函数对象都是属于window的对象,window.fu1();和fu1();输出结果一样,一般属于window的对象书写时省略window
fu1(); // 普通函数this指向的是window对象
function Fnc(age) {
this.age = 18;
console.log(this);
}
var fun = new Fnc(18); // 构造函数this指定的是对象的本身
var but = document.querySelector('button');
but.onclick = function (){
console.log(this);
}; // 触发事件中,谁触发this指向谁
</script>
</body>