本文已参与「新人创作礼」活动,一起开启掘金创作之路。
一、JS内置对象
JS内部已经内置了不少对象,类似于Python中的内置模块,可以直接使用,并且对象一般不需要导入,可以直接使用
1.Math对象
Math对象是一个处理数学相关的对象,可以用来执行在数学相关的内容
具体使用方法如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// Math对象直接引入
// 1,开平方
console.log(Math.sqrt(4));
// 2.幂运算 2的3次方
console.log(Math.pow(2, 3));
// 3.绝对值
console.log(Math.abs(-1));
// 4.Π
console.log(Math.PI);
// 5.四舍五入
console.log(Math.round(4.5));
// 6.向上取整
console.log(Math.ceil(2.1));
// 7.向下取整
console.log(Math.floor(2.6));
// 8.随机数
// Math.random()*m+n:生成n~(m+n)之间的随机数
console.log(Math.random()); //[0,1) 取不到1
console.log(Math.round(Math.random()*10)); //[0,10]
// 9.最大值
console.log(Math.max(1, 7, 5, 3));
//10.最小值
console.log(Math.min(1, 2, 5, 0));
</script>
</body>
</html>
2.Date对象
日期也是常用对象之一,基本和常用的方法都是需要了解和熟悉
具体使用方法如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// 定义一个时间日期对象
var time = new Date()
// 1.获取年份
console.log(time.getFullYear());
// 2.获取月份:0——11 ,所以后面要加一
console.log(time.getMonth()+1);
// 3.获取日期
console.log(time.getDate());
// 4.获取时间
console.log(time.getHours());
// 5.获取分钟
console.log(time.getMinutes());
// 6.获取秒钟
console.log(time.getSeconds());
// 7.获取星期
console.log(time.getDay());
// 8.时间戳:从1970 1月1号 0点0分0秒开始计算的,每一秒加一
// 东八区是从8点开始计时,得到的数字可以在网页搜索时间戳转换工具进行转换,会得到当前时间
var times = Date.now()
document.write(times)
console.log(times);
</script>
</body>
</html>
二、JS的window对象
Window对象是所有客户端JS特性和API的主要接入点。它表示Web浏览器的一个窗口或窗体,并且可以用标识符window来引用它。Window对象定义了一些属性和方法,比如:alert()方法、非常重要的document属性以及计时器等等,下面主要对计时器进行介绍。具体代码操作如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--1.a标签可以实现跳转网页-->
<!--<a href=""></a>-->
<!--2.JS通过button按钮实现跳转页面-->
<button>按钮</button>
<script>
// 弹窗完整写法
// window.alert(456)
// 1.定时器:1000毫秒即1秒 以指定时间为周期循环执行
// 完整的写法有window.setInterval,不写window也可以
// 里面可以写函数,也可以写函数方法名
var time1 = setInterval(function () {
console.log(1);
},1000)
// 2.延时器:以指定时间为周期循环执行一次
var time2 = setTimeout(function(){
console.log(2);
},1000)
clearInterval(time1) //清除定时器
clearTimeout(time2) //清除延时器
// 1.JS实现跳转到指定网页功能
var obtn = document.getElementsByTagName("button")[0]
// https://www.baidu.com/
obtn.onclick = function(){
// 1)方法一:window.location.href 在当前页面进行跳转
// window.location.href = "https://www.baidu.com/"
// 2)方法二:window.open 打开新的页面进行跳转
window.open("https://www.baidu.com/")
}
</script>
</body>
</html>