JavaScript Date、Math对象、杂项


 

Date 时间日期

  // 创建Date对象
  var date1=new Date();  //当前日期时间
  var date2=new Date(2020, 5, 1);  //指定日期时间,年,月,日,时,分,秒,毫秒,参数个数可变,但顺序必需按这个来
  var date3=new Date(1222222222222); //到1970.1.1 00:00:00的时间戳,毫秒
方法 描述
setFullYear() 设置4位数的年份
setMonth() 月份,0-11
setDate() 日,1-31
setHours() 时,0-23
setMinutes() 分,0-59
setSeconds() 秒,0-59
setMilliseconds() 毫秒,0-999
setTime() 设置时间戳,毫秒

均有对应的get方法。

Math 数学运算

  Math.PI  //常量,π


  Math.round(2.678)  //四舍五入,只保留整数
  Math.ceil(4.2)  //向上取整,4.2=>5,-4.2=>-4
  Math.floor(4.2)  //向下取整,4.2=>4,-4.2=>-5


  Math.pow(2, 3)  //乘方,2^3
  Math.sqrt(64)  //算术平方根
  Math.abs(-1)  //绝对值


  // 参数均为弧度
  Math.sin(x) 
  Math.cos(x)
  Math.tan(x)


  Math.min(0, 450, 35, 10, -8, -300, -78)  //返回最小数
  Math.max(0, 450, 35, 10, -8, -300, -78)  //最大数


  Math.random();  //返回[0,1)上的随机数

  // random常与floor|ceil|round搭配使用,返回随机整数
  Math.floor(Math.random() * 10);  // 返回一个[0,10)上的随机整数

switch语句

  function f(role){
    switch(role){
      case "user":
        console.log("user");
        break;
      case "admin":
        console.log("admin");
        break;
      default:
        console.log("不合法的角色");
    }
  }

  f("admin");

比较运算符

运算符 描述
== 等于,不管类型,只要值相等,就认为相等。eg. “8”==8 true
!= 不等于,不管类型,只要值不等,就认为不等
=== 全等,值和类型都要相同才为true
!== 不全等,值和类型只要有1个不同,就认为不全等

逻辑运算符

假:false、数字0、空串、null、undefined、NAN
真: 除开上面假的,都是真

&& 与
|| 或
! 非

this关键字

使用位置不同,this指代的内容不同

  • 在方法中,this 指代方法所属的对象
  • 在事件监听的处理函数中,this指代绑定事件监听的元素

命名规范

  // 变量名、函数名均使用camel写法(驼峰命名)
  var goodsPrice=10.00;

  function getGoodsPrice(){

  }
  

  // 常量名全大写,单词之间下划线连接
  var ORDER_STATUS="paid";

猜你喜欢

转载自blog.csdn.net/chy_18883701161/article/details/106160731
今日推荐