javascript 中对象分为:自定义对象,内置对象(),浏览器对象
前两个属于js得基础,属于ECMAScript;第三个是js独有得(以后学到补充)
内置对象是指js语言中自带得一些对象,懒人帮手
如何查阅MDN文档 (重点,如果文档你都不会查阅。。那就太笨了)
记住这四大步骤
1.查看该方法得功能
2.查看里面参数的意义和类型 ([]中括号代表可以有参数也可以没有)
3.查看返回值的意义和类型
4.最后自己运行一下
Math数学对象
不是一个构造函数,所以我们不需要new来调用,直接使用属性和方法就好了
console.log(Math.PI);
console.log(Math.max(1,99,3));//返回99
console.log(Math.max('pink',99));//返回NaN
console.log(Math.max());//返回-Infinity
自己手动封装一个求最大值
var str = {
max:function() {
var max = arguments[0];
for(i=1;i<arguments.length;i++) {
if(max<arguments[i]) {
max = arguments[i];
}
}
return max;
}
}
console.log(str.max(1,3,4));
// 1.绝对值
console.log(Math.abs(1)); //1
console.log(Math.abs(-1)); //1
console.log(Math.abs('1')); //1
console.log(Math.abs('pink'));//NaN
//三种取整得方法
//(1).向下取整floor 往最小取值
console.log(Math.floor(1.1)); //1
console.log(Math.floor(1.9)); //1
//(2).向上取整ceil 往最大取值
console.log(Math.ceil(1.1));//2
console.log(Math.ceil(1.9));//2
//(3).四舍五入round .5特殊往大得取值
console.log(Math.round(1.1));//1
console.log(Math.round(1.5));//2
console.log(Math.round(1.9));//2
console.log(Math.round(-1.5));//1
//Math对象随机数方法 random() 返回一个随机得小数 0 =<随机数 <1
// 2.这个方法不跟参数
// 3.代码验证
// 4.取到两个数之间随机整数,并且包含2个整数
function getRandom(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min; //这个是核心算法,可以直接拿来用
}
console.log(getRandom(1,10));
//随机点名
var arr = ['z','s','f'];
console.log(arr[getRandom(0,arr.length-1)]);
课堂案例
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var random = getRandom(1, 50);
//课程案例:随机一个1-10的随机数,但是没有输入次数,所以用while循环更好
// while(true) { //死循环
// if (re > random) {
// alert('大了还有');
// } else if (re < random) {
// alert('小了还有');
// } else {
// alert('对了');
// break;
// }
// }
//课程案例升级版,随机1-50的数,但是有输入次数限制,10次,所以用for循环更好
for (i = 10; i >= 0; i--) {
var re = prompt('请猜数字:');
if (i == 0) {
alert('次数不够,强制结束');
break;
}
else if (re > 50) {
alert('50以内的,你别整事');
} else if (re > random) {
alert('大了还有' + (i - 1) + '次');
} else if (re < random) {
alert('小了还有' + (i - 1) + '次');
} else {
alert('对了');
break;
}
}
Data 日期对象
是一个构造函数 必须用new来调用构造函数
// 1.如果Date没有参数,那么就返回系统当前时间
var date = new Date();
console.log(date);
// 2.写参数就用字符串型的 '2022-1-1 9:9:9';
var date1 = new Date('2022-1-1 9:9:9');
console.log(date1);
//先学习后面的,以后再更新