内置对象(系统自带)
Math、Date、Array、Object…
Math 数学内置对象
1.
Math.PI 圆周率
console.log(Math.PI); //π
Math.max( ) 最大值
Math.min( ) 最小值
console.log(Math.max(10,20,3,6,9)); //20
console.log(Math.min(10,20,3,6,9)); //3
Math.abs( ) 绝对值
console.log(Math.abs('-1')); //1
console.log(Math.abs('string')); //NaN
console.log(Math.abs()); //
Math.random( ) [0,1)之间的随机数
console.log(Math.random()); [0,1)之间的随机数
//获取0-5之间的随机数
console.log(Math.random()*5);
//获取0-5之间的整数
console.log(parseInt(Math.random()*5));
//获取1-5之间的数字
console.log(parseInt(Math.random()*5 + 1)); //1-5
Math.ceil( ) 向上取整
console.log(Math.ceil(12.3)); //13
Math.floor( ) 向下取整
console.log(Math.floor(12.3)); //12
Math.round( ) 四舍五入
console.log(Math.round(12.3)); //12
Math.pow( ) 求指数次幂
console.log(Math.pow(2,4)); //16 2的4次方
Math.sqrt( ) 求平方根
console.log(Math.sqrt(16)); //4
Date 时间戳
var dt = new Date(); //获取时间 年月日时分秒 系统自带
console.log(dt);
var year = dt.getFullYear(); //获取年
console.log(year); // 2022
var month = dt.getMonth() + 1; //获取月份要+1
console.log(month); //2
var day = dt.getDate(); //获取天
console.log(day); //24
var hours = dt.getHours(); //获取小时
console.log(hours); //21
var minute = dt.getMinutes(); //获取分钟
console.log(minute);
var second = dt.getSeconds(); //获取秒
console.log(second);
var week = dt.getDay(); //获取周几
console.log(week);
需求:定义一个函数,获取到年月日星期
function dateTime(){
var dt = new Date(); //获取到全部时间
var y = dt.getFullYear(); //获取年
var m = dt.getMonth(); //获取月
var d = dt.getDate(); //获取日
var week = dt.getDay(); //获取星期
switch(week){ //用switch来判断
case 1 :
week = "星期一";
break;
case 2 :
week = "星期二";
break;
case 3 :
week = "星期三";
break;
case 4 :
week = "星期四";
break;
case 5 :
week = "星期五";
break;
case 6 :
week = "星期六";
break;
case 0 :
week = "星期日";
break;
}
return y + "年" + m + "月" + d + "天" + week; // 返回拼接
}
var result = dateTime();
console.log(result);
需求:随机点名
var arr = ["鸣人","佐助","春野樱","宁次","李洛克","天天","鹿丸","丁次","我爱罗","勘九郎","带土","卡卡西","凯","水门"];
var suiji = parseInt(Math.random() * arr.length);
alert(arr[suiji]);
需求:封装函数实现系统max最大值方法
function myMax(){
var max = arguments[0]; //假设max为第一个
for(var i = 0; i < arguments.length; i++){
//判断
if(max < arguments[i]){
max = arguments[i];
}
}
return max;
}
var result = myMax(10,20,30,100,50);
console.log(result); //100
需求:随机生成一个颜色(数字0-9,字母a-f)
function getColor(){
var str = "#"; //颜色是以#开头的
//定义一个数组
var arr = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
for(var i = 0; i < 6; i++){ //颜色代码6位数
var num = parseInt(Math.random() * arr.length); //取整
str += arr[num];
}
return str;
}
var result = getColor();
console.log(result);