JS Math对象、日期对象、函数、定时器

Math对象

  • 开平方:sqrt
  • 绝对值:abs
  • π:PI
  • x的y次方:pow
  • 四舍五入取整:round
  • 向下取整:floor
  • 向上取整:ceil
  • 最大值:max
  • 最小值: min
  • 随机数:random
var br = "<br>";
document.write(Math.sqrt(9) + br);//开平方
document.write(Math.abs(-9) + br);//绝对值
document.write(Math.PI + br);//π:3.141592653589793....
document.write(Math.pow(2, 10) + br);//x的y次方
document.write(Math.round(3.5) + br);//四舍五入取整
document.write(Math.floor(3.9) + br);//向下取整
document.write(Math.ceil(3.1) + br);//向上取整
document.write(Math.max(8, 2, 4, 21) + br);//最大值
document.write(Math.min(8, 2, 4, 21) + br);//最小值
document.write(Math.random() * 100 + br);//随机数:0-1

日期对象

  • 获取当前时间:Date()
  • 获取年:getFullYear
  • 获取月:getMonth
  • 获取日:getDate
  • 获取周几:getDay
  • 获取时:getHours
  • 获取分:getMinutes
  • 获取秒:getSeconds
  • 时间戳:Date.now()
var br = "<br>";
var datetime = new Date();
document.write(Date() + br);//获取当前时间
document.write(datetime.getFullYear() + br);//获取年
document.write(datetime.getMonth() + 1 + br);//获取月(0-11)
document.write(datetime.getDate() + br);//获取日
document.write(datetime.getDay() + br);//获取周几
document.write(datetime.getHours() + br);//获取时
document.write(datetime.getMinutes() + br);//获取分
document.write(datetime.getSeconds() + br);//获取秒
document.write(Date.now() + br);//时间戳

函数

  • 定义函数:function funName(){}
  • 函数分类
    • 有名函数
//有名函数
//不定参
function func() {
    return arguments[2] * arguments[4]
}
document.write(func(0, 1, 2, 3, 4));
- 匿名函数
// 匿名函数一般充当事件函数
var box = document.getElementById("box");
box.onclick = function () {
    alert("===")
}
  • 作用域
    • 加var定义,子作用域不会修改父作用域的值
var num = 111;
function eject() {
    var num = 999;
    alert(num)//999
}
alert(num);//111
eject();
alert(num);//111
- 不加var定义,子作用域会修改父作用域的值
var num = 111;
function eject() {
    num = 999;
    alert(num)//999
}
alert(num);//111
eject();
alert(num);//999

定时器

  • 设置定时器:setTimeout(只执行一次)
  • 清除定时器:clearTimeout
  • 设置定时器:setInterval(一直执行)
  • 清除定时器:clearInterval
function log() {
    console.log("---")
}
//只执行一次
setTimeout(log, 1000);
//一直执行
var timer = setInterval("log()",1000);

var btn = document.getElementsByTagName("button")[0];
btn.onclick = function () {
    //清除定时器
    clearInterval(timer);
}
posted @ 2019-12-13 19:00  三个零  阅读(339)  评论(0编辑  收藏  举报