注意
平常:
针对数组、字符串操作最多
字符串真实操作都在正则表达式
1.数学方法 Math.xxx()
数学方法
+ 操作数字的方法
+ 通用语法: Math.xxx()
1. random()
+ 语法: Math.random(数字)
+ 返回值: 0 ~ 1 之间的随机小数, 包含0不包含1
2. round()
+ 语法: Math.round(数字)
+ 返回值: 四舍五入后取整的结果
负数没有取整
// -3.4 -4+0.6 -4+1=-3
// -3.5 -4+0.5 -3
// -3.6 -4+0.4 -4+0=-4
3. ceil()
+ 语法: Math.ceil(数字)
+ 返回值: 向上取整的结果
4. floor()
+ 语法: Math.floor(数字)
+ 返回值: 向下取整的结果
5. abs()
+ 语法: Math.abs(数字)
+ 返回值: 取绝对值
6. pow()
+ 语法: Math.pow(底数, 指数)
+ 返回值: 取幂结果
7. sqrt()
+ 语法: Math.sqrt(数字)
+ 返回值: 算数平方根
8. max()
+ 语法: Math.max(数字1, 数字2, ...)
+ 返回值: 若干个数字中的最大值
9. min()
+ 语法: Math.min(数字1, 数字2, ...)
+ 返回值: 若干个数字中的最小值
10. PI
+ 语法: Math.PI
+ 得到: 一个近似 π 的值
2.Number方法
console.log( Number.isInteger(3.5))
console.log( Number.isInteger(3))
console.log( Number.isInteger(2**64))
console.log(Number.isSafeInteger(2**64))
console.log(Number.isSafeInteger(-3))
console.log(Number.NEGATIVE_INFINITY)
console.log(Number.POSITIVE_INFINITY)
console.log(Number.isFinite(Number.NEGATIVE_INFINITY))
console.log(Number.MAX_SAFE_INTEGER)
console.log(Number.MIN_SAFE_INTEGER)
console.log(Number.MAX_VALUE)
console.log(Number.MIN_VALUE)
var n=30000;
var m=0.000005
console.log(n.toString(2))
console.log(n.toFixed(2))
console.log(n.toExponential(2))
console.log(n.toPrecision(2))
console.log(m.toExponential(3))
console.log(m.toPrecision(3))
3.String方法
字符串常用方法
+ 专门用来操作字符串的方法
+ 通用语法: 字符串.xxx()
+ 所有的字符串方法, 都不会改变原始字符串, 而是以返回值的形式给出结果
1. charAt()
+ 语法: 字符串.charAt(索引)
+ 返回值: 指定索引位置的字符
=> 如果没有这个索引位置, 返回的是 空字符串
2. charCodeAt()
+ 语法: 字符串.charCodeAt(索引)
+ 返回值: 指定索引位置的字符的编码, 转换成十进制给到你
=. 如果没有这个索引位置, 返回的是 NaN
3. toUpperCase()
+ 语法: 字符串.toUpperCase()
+ 返回值: 转换好大写的字符串
4. toLowerCase()
+ 语法: 字符串.toLowerCase()
+ 返回值: 转换好小写的字符串
5. substr()
+ 语法: 字符串.substr(开始索引, 多少个)
+ 返回值: 截取部分字符串
6. substring()
+ 语法: 字符串.substring(开始索引, 结束索引)
+ 特点: 包前不包后
+ 返回值: 截取部分字符串
7. slice()
+ 语法: 字符串.slice(开始索引, 结束索引)
+ 特点: 包前不包后, 可以填写负整数
+ 返回值: 截取部分字符串
8. replace()
+ 语法: 字符串.replace(换下字符, 换上字符)
+ 注意: 只能替换找到的第一个字符片段
+ 返回值: 替换好一个内容以后的字符串
9. split()
+ 语法:
=> 字符串.split(切割符)
=> 字符串.split(切割符, 保留数组长度)
+ 作用: 按照切割符号把字符串切割成多段, 存储在一个数组内
+ 返回值: 必然是一个数组数据类型
=> 数组内存储的是分隔开的每一段内容
10. concat()
+ 语法: 字符串.concat(字符串2, 字符串3, ...)
+ 返回值: 拼接好的字符串
11. indexOf()
+ 语法:
=> 字符串.indexOf(字符串片段)
=> 字符串.indexOf(字符串片段, 开始索引)
+ 返回值:
=> 该字符串片段首字母的索引位置
=> 如果没有该字符串片段, 那么就是 -1
12. lastIndexOf()
+ 语法:
=> 字符串.indexOf(字符串片段)
=> 字符串.indexOf(字符串片段, 开始索引)
+ 返回值:
=> 该字符串片段首字母的索引位置
=> 如果没有该字符串片段, 那么就是 -1
13. trim()
+ 语法: 字符串.trim()
+ 返回值: 去除首尾空白以后的字符串
14. trimLeft() / trimStart()
+ 语法:
=> 字符串.trimStart()
=> 字符串.trimleft()
+ 返回值: 去除开始位置空白内容后的字符串
15. trimRight() / trimEnd()
+ 语法:
=> 字符串.trimRight()
=> 字符串.trimEnd()
+ 返回值: 去除结束位置空白内容后的字符串
4.时间 Date方法
时间对象的常用方法
获取 设置
getFullYear() setFUllYear()
getMonth() setMonth()
getDate() setDate()
getHours() setHours()
getMinutes() setMinutes()
getSeconds() setSeconds()
getMilliseconds() setMilliseconds()
getDay() -
getTime() setTime()
所有方法 带有 UTC 表示 获取和设置 世界标准时间
没有 UTC 表示 获取和设置 当前终端时间
var time = new Date()
console.log(time)
var year = time.getFullYear()
var month = time.getMonth()
var date = time.getDate()
var hours = time.getHours()
var minutes = time.getMinutes()
var seconds = time.getSeconds()
var ms = time.getMilliseconds()
var day = time.getDay()
var t = time.getTime()
console.log(year, month, date, hours, minutes, seconds, ms, day, t)
var time = new Date()
console.log('初始时间 : ', time)
time.setFullYear(1998)
time.setMonth(6)
time.setDate(1)
time.setHours(12)
time.setMinutes(34)
time.setSeconds(56)
time.setMilliseconds(123)
time.setTime(123456789)
console.log('设置之后 : ', time)
console.log('设置之后 : ', time.getMilliseconds())
4.1 时间小案例-秒表
<div id="div0">00:00:00</div>
<button id="startBn">开始</button>
<button id="stopBn">停止</button>
<script>
var div0,startBn,stopBn,startDate
var bool=false,prevTime=0
init()
function init(){ //初始化
//1.获取元素
div0=document.getElementById("div0")
startBn=document.getElementById("startBn")
stopBn=document.getElementById("stopBn")
//绑定点击事件
startBn.onclick=startHandler
stopBn.onclick=stopHandler
setInterval(animation,10)
}
//2.按下开始
function startHandler(){
bool=!bool
startBn.innerHTML=bool ? "暂停" : "开始"
if(bool){ //当布尔值为true时 开始运行
// 点击开始时 的时间
startDate=new Date()
}else{
prevTime+=Date.now()-startDate.getTime()
}
}
//3.按下暂停
function stopHandler(){
bool=false
prevTime=0
startBn.innerHTML="开始"
}
//4.运行时的计算
function animation(){
if(!bool) return
//当前时间-开始时date 时间差 + 上一次记录的时间(prevTime) 方便继续计时
var time=Date.now()-startDate.getTime()+prevTime
var ms=~~((time%1000)/10)
var s=~~(time/1000)%60
var m=~~((time-ms*10-s*1000)/1000/60)
//在网页输出出来 把 m,s,ms 转换成字符串 padStart(2,"0")表示不够两位补 0(因为时间是00:00:00)
div0.innerHTML=String(m).padStart(2,"0")+":"+String(s).padStart(2,"0")+":"+String(ms).padStart(2,"0")
}
4.2 时间小案例-中文时间
<div id="div0"></div>
<script>
// 二零二二年六月九日 星期四 十二点零五分三十秒
var div0
var list=["零","一","二","三","四","五","六","七","八","九","十"]
init()
function init(){
div0=document.getElementById("div0")
setInterval(animation,16)
}
function animation(){
var date=new Date()
var year=date.getFullYear().toString()
year=list[year[0]]+list[year[1]]+list[year[2]]+list[year[3]]+"年"
// year=year.split("").reduce(function(v,t){ //上述也可以这样写
// return v+list[t]
// },"")+"年"
var month=getCNNumber(date.getMonth()+1)+"月"
var day=getCNNumber(date.getDate())+"日"
var week=date.getDay()===0 ? "星期日" : "星期"+list[date.getDay()]
var hours=getCNNumber(date.getHours())+"点"
var minutes=getCNNumber(date.getMinutes(),true)+"分"
var seconds=getCNNumber(date.getSeconds(),true)+"秒"
div0.innerHTML=year+month+day+" "+week+" "+hours+minutes+seconds
}
function getCNNumber(num,bool){
if(num>=100 || num<0) throw new RangeError(num+"is error number!")
if(num<10) return !bool ? list[num] : "零"+list[num]
if(num===10 || num===0) return list[num]
if(num%10===0) return list[num/10]+"十"
if(num<20) return "十"+list[num%10]
return list[~~(num/10)]+"十"+list[num%10]
}
</script>
5.认识BOM
DOM Document Object Model 文档对象模型 页面中的部分 Document
BOM Browser Object Model 浏览器对象模型 浏览器部分 Browser
ECMAScript 标准 所有浏览器都必须支持
Model 基础结构
Object Model 对象有属性和方法 任意添加属性和方法
浏览器的根节点 window->document\history...
文档的根节点 document ->html->head\body->
BOM包含了DOM
BOM
window 父级
document 子级
location 子级
history 子级
screen 子级
navigator 子级
5.1 window对象
window.open()
open("http://www.163.com");
open("http://www.163.com","_blank","width=200,height=200")
close();
console.log(innerWidth,innerHeight);
console.log(outerWidth,outerHeight);
console.log(screenX,screenY);
console.log(screenLeft,screenTop);
1.浏览器滚动到
+ 浏览器滚动条定位
+ 语法: window.scrollTo()
+ 通过传递不同的参数, 来实现不同的效果
2.传递数字
+ 语法: window.scrollTo(x, y)
=> x 表示横向滚动条位置
=> y 表示纵向滚动条位置
+ 注意: 如果你是传递数字, 必须传递两个, 一个会报错
+ 只能瞬间定位(秒滚动)
3.传递对象
+ 语法: window.scrollTo({ top: yyy, left: xxx })
+ 默认是瞬间定位, 加一个 behavior: 'smooth' 属性表示是否平滑滚动(可平滑滚动)
4. 提示框
+ 语法: window.alert(提示文本)
+ 表现形式: 一个弹出层 + 提示文本 + 确定按钮
+ 返回值: undefined
5. 询问框
+ 语法: window.confirm(提示文本)
+ 表现形式: 在 提示框 的基础上 + 取消按钮
+ 返回值: 一个布尔值
-> 如果你点击的是 确定, 那么就是 true
-> 如果你点击的是 取消, 那么就是 false
6. 输入框
+ 语法: window.prompt(提示文本)
+ 表现形式: 在 询问框 的基础上 + 文本框
+ 返回值:
-> 如果你点击的是 确定, 那么就是 文本框 内输入的内容, 必然是一个字符串类型
-> 如果你点击的是 取消, 那么就是 null
5.2 document
卷去的高度
+ 语法:
=> document.documentElement.scrollTop
-> 页面有 DOCTYPE 标签的时候能获取到值
=> document.body.scrollTop
-> 页面没有 DOCTYPE 标签的时候能获取到值
+ 兼容: 使用 || 短路表达式
=> var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
卷去的宽度
+ 语法:
=> document.documentElement.scrollLeft
-> 页面有 DOCTYPE 标签的时候能获取到值
=> document.body.scrollLeft
-> 页面没有 DOCTYPE 标签的时候能获取到值
+ 兼容: 使用 || 短路表达式
=> var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
5.3 location对象
location.reload()
location.href="http://www.163.com"
location.assign("http://www.163.com")
location.replace("http://www.163.com")
var bn=document.getElementById("bn");
bn.onclick=function(){
location.href="http://www.163.com"
console.log(location.href);
location.assign("http://www.163.com")
location.replace("http://www.163.com")
}
console.log(location.hash)
console.log(location.search)
console.log(location.protocol);
console.log(location.host);
console.log(location.hostname);
console.log(location.pathname);
console.log(location.port);
5.4 history对象
history.back();
history.forward();
history.go(1);
history.go(-1);
history.go(0);
console.log(history.state);
history.pushState();
history.replaceState();
当触发历史记录改变时,触发事件
window.onpopstate=function(){
}
当hash数据发生改变时触发事件
window.onhashchange=function(){
}
5.5 screen对象
console.log(screen.availWidth,screen.availHeight);
console.log(screen.width,screen.height);
5.6 navigator对象
console.log(navigator.userAgent)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36
navigator.geolocation.getCurrentPosition(function(p){
console.log(p);
},function(err){
})
6.BOM小案例-切换页面
var list={
fruits:["葡萄","西瓜","火龙果","榴莲","苹果","橘子","香蕉"],
vegetable:["西红柿","冬瓜","黄瓜","白菜","南瓜","蒜薹","菠菜"],
grain:["小米","大米","面","红豆","花生油","绿豆","橄榄油"],
meat:["鸡肉","牛肉","羊肉","猪头肉","鸭","鱼","驴肉"],
}
var div0,lis,prev;
init();
function init(){
lis=Array.from(document.getElementsByTagName("li"));
div0=document.getElementById("div0");
lis.forEach(function(item){
item.onclick=clickHandler;
})
changePrev(lis[0]);
changeContent(lis[0].id);
}
function clickHandler(){
changePrev(this);
changeContent(this.id);
}
function changePrev(target){
if(prev){
prev.style.backgroundColor="skyblue";
}
prev=target;
prev.style.backgroundColor="steelblue";
}
function changeContent(id){
div0.innerHTML=list[id].join("-")
}
7.BOM小案例-切换页面-hash 必须会
<ul class="clear">
<li id="fruits"><a href="#fruits" id="fruits_1">水果</a></li>
<li id="vegetable"><a href="#vegetable" id="vegetable_1">蔬菜</a></li>
<li id="grain"><a href="#grain" id="grain_1">粮油</a></li>
<li id="meat"><a href="#meat" id="meat_1">禽肉</a></li>
</ul>
<div id="div0">
</div>
<script>
var list={
fruits:["葡萄","西瓜","火龙果","榴莲","苹果","橘子","香蕉"],
vegetable:["西红柿","冬瓜","黄瓜","白菜","南瓜","蒜薹","菠菜"],
grain:["小米","大米","面","红豆","花生油","绿豆","橄榄油"],
meat:["鸡肉","牛肉","羊肉","猪头肉","鸭","鱼","驴肉"],
}
var div0,prev;
init();
function init(){
div0=document.getElementById("div0");
window.onhashchange=hashChangeHandler;
document.getElementById("fruits_1").click();
}
function hashChangeHandler(){
var id=location.hash.slice(1);
changeContent(id);
changePrev(document.getElementById(id));
}
function changeContent(id){
div0.innerHTML=list[id].join("-")
}
function changePrev(target){
if(prev){
prev.style.backgroundColor="skyblue";
}
prev=target;
prev.style.backgroundColor="steelblue";
}
</script>
8.BOM小案例-切换页面-history 必须会
<ul class="clear">
<li id="fruits">水果</li>
<li id="vegetable">蔬菜</li>
<li id="grain">粮油</li>
<li id="meat">禽肉</li>
</ul>
<div id="div0"> </div>
<script>
var list={
fruits:["葡萄","西瓜","火龙果","榴莲","苹果","橘子","香蕉"],
vegetable:["西红柿","冬瓜","黄瓜","白菜","南瓜","蒜薹","菠菜"],
grain:["小米","大米","面","红豆","花生油","绿豆","橄榄油"],
meat:["鸡肉","牛肉","羊肉","猪头肉","鸭","鱼","驴肉"],
}
var div0,lis,prev;
init();
function init(){
lis=Array.from(document.getElementsByTagName("li"));
div0=document.getElementById("div0");
lis.forEach(function(item){
item.onclick=clickHandler;
})
window.onpopstate=popstateHandler;
var state=history.state || lis[0].id;
changePrev(document.getElementById(state));
changeContent(state);
history.replaceState(state,state);
}
function popstateHandler(){
changePrev(document.getElementById(history.state))
changeContent(history.state)
}
function clickHandler(){
if(prev===this) return;
changePrev(this);
changeContent(this.id);
history.pushState(this.id,this.id,"");
}
function changeContent(id){
div0.innerHTML=list[id].concat("-")
}
function changePrev(target){
if(prev){
prev.style.backgroundColor="skyblue";
}
prev=target;
prev.style.backgroundColor="red";
}