續(xù) <一>
九、JavaScript常見內(nèi)置類
9.1 原始類型的包裝類
- 基本數(shù)據(jù)類型也可以調(diào)用屬性
- 在理論上來說它們是沒有辦法獲取屬性或者調(diào)用方法的
- 原始類型是簡單的值,默認(rèn)并不能調(diào)用屬性和方法
- js 為了可以使其獲取屬性和調(diào)用方法,對其封裝了對應(yīng)的包裝類型
- 普通字符串==》包裝類型
- 常見的包裝類型
- String、Number、Boolean、Symbol、BigInt
9.2 包裝類型的使用過程
- 根據(jù)初始值,創(chuàng)建一個原始類型對應(yīng)的包裝類型對象
- 調(diào)用對應(yīng)的屬性或者方法,返回一個新的值
- 創(chuàng)建的包裝類對象被銷毀
- 但是通常 js 引擎會進(jìn)行優(yōu)化,跳過包裝類的過程在內(nèi)部直接完成屬性的獲取或者方法的調(diào)用
9.3 Number 類補(bǔ)充
- 具有自己的屬性
- 類屬性
- 具有實(shí)例方法
- 實(shí)例方法:通過對象來調(diào)用
- toFixed()
- toString()
<script>
var num = 19//new Number(num)
// integer:整數(shù)
// 類屬性
console.log(Number.MAX_SAFE_INTEGER);
// 對象方法
var num1 = 3.333454
// 轉(zhuǎn)化成字符串類型
console.log(num1.toString());
// 轉(zhuǎn)換為二進(jìn)制
console.log(num1.toString(2));
console.log(123..toString());
// 保留三位小數(shù)
console.log(num1.toFixed(2));
// 類方法
// 字符串轉(zhuǎn)數(shù)字類型
var str = "123.24"
Number(str)//不做區(qū)分浮點(diǎn)數(shù)和整數(shù)
Number.parseInt(str)
Number.parseFloat(str)
// window對象上面
console.log(parseInt(str));
</script>
9.4 Math 對象
- 是一個對象類型,不是構(gòu)造函數(shù)
<body>
<script>
console.log(typeof Math);
// Math對象的屬性
console.log(Math.PI);
var num = 3.13
console.log(Math.floor(num));
console.log(Math.ceil(num));
console.log(Math.round(num));
// random:[0,1)
console.log(Math.random());
// 需求5~50的隨機(jī)數(shù)
// [5,20)
var randomNum = Math.floor(Math.random()*45)+5
</script>
</body>
9.5 Number、Math 的常見操作
9.5.1 Number 類的操作
- 類屬性
- Number.MAX_SAFE_INTEGER 最大安全整數(shù)
- Number.MIN_SAFE_INTEGER 最小安全整數(shù)
- 實(shí)例方法
- toString(base),將數(shù)字轉(zhuǎn)成字符串,并且按照base進(jìn)制進(jìn)行轉(zhuǎn)化
- toFixed(digits),格式化一個數(shù)字,保留digits位的小數(shù),會四舍五入
- 類方法
- Number.parseInt(string[, radix]),將字符串解析成整數(shù),也有對應(yīng)的全局方法parseInt;
- Number. parseFloat(string),將字符串解析成浮點(diǎn)數(shù),也有對應(yīng)的全局方法parseFloat;
9.5.2 Math 的常見操作
-
屬性
- Math.PI:圓周率
-
常見的方法
- Math.floor:向下舍入取整
- Math.ceil:向上舍入取整
- Math.round:四舍五入取整
- Math.random:生成0~1的隨機(jī)數(shù)(包含0,不包含1)
- Math.pow(x, y):返回x的y次冪
-
公式: [a,b)的隨機(jī)數(shù)
- y=a,x=b-a, Math.floor(Math.random() * x) + y
9.6 String 類的補(bǔ)充
- 屬性
- length:獲取字符串長度
- 訪問某一個位置對應(yīng)的字符
- 遍歷
<script>
// 屬性
var message = "lili"
console.log(message.length);
// 訪問某一個位置對應(yīng)的字符
console.log(message[3]);//超出范圍:undefined
console.log(message.charAt(3));//超出范圍:空字符串
// 3. 字符串的遍歷
// 3.1 for普通遍歷
for(let i =0;i<message.length;i++){
console.log(message[i]);
}
// 3.2 for..of遍歷 -> 迭代器:目前就字符串和數(shù)組
// 對象不支持for...of
// string對象內(nèi)部將字符串變成了一個可迭代對象
for(var char of message){
console.log(char);
}
</script>
- 字符串不能修改
// 4. 修改字符串
// 創(chuàng)建新的字符串,讓變量指向了一個新的值
message = "加加加"
// 嚴(yán)格的修改字符串:修改之前的字符串內(nèi)部
message[1] = "0"
// 所有字符變成大寫:生成新的字符串
var message1 = message.toUpperCase()
console.log(message1);
// 變成小寫
var message2 = message.toLowerCase()
- 查找字符串
- indexOf
- includes
- startWith
- endWith
- replace
// 判斷一個字符串中是否有另外一個字符串
// 5.1 indexOf(searchString,fromIndex)
/*
index:搜索到,返回搜索字符串所在的索引位置
沒有搜索到,返回-1
*/
var index = message2.indexOf(name)
console.log(index);
// 存在
if (message2.indexOf(name) !== -1) {
console.log("message2中包含name");
} else {
console.log("message2中不包含name");
}
// 5.2 includesES6新增語法,用來判斷包含關(guān)系
if (message2.includes(name)) {
console.log("哈哈哈哈好好照顧自己~~");
}
// 5.3 startWith:是否以xxx開頭
if (message2.startsWith("my")) {
console.log("messages以my開頭");
}
// 5.4 endWith:是否以xxx開頭
// 5.5 replace:替換字符串("替換誰",正則表達(dá)式、代替值、函數(shù))
var newMessage = message2.replace("lili", "涵涵")
console.log(newMessage);
var newMessage2 = message2.replace("lili", function () {
// 使用函數(shù)返回的值去替代字符串
return "kobe"
})
console.log(newMessage2);
// 6. 獲取子字符串:slice、substring、substr
// slice
var clothes = "衣服包包鞋子"
console.log(clothes.slice(3));//截到最后
console.log(clothes.slice(1, 3));
// substr:瀏覽器是否支持
- 獲取子字符串:slice
// 6. 獲取子字符串:slice、substring、substr
// slice
var clothes = "衣服包包鞋子"
console.log(clothes.slice(3));//截到最后
console.log(clothes.slice(1, 3));
// substr:瀏覽器是否支持
- 字符串拼接
// 7. 字符串的拼接
// 7.1 +
var str1 = "lili"
var str2 = "哈啰"
var newStr = str1 + str2
// 7.2 concat:支持鏈?zhǔn)秸{(diào)用,參數(shù)是可變參數(shù)...
var newStr2 = str1.concat(str2, newStr)
- 刪除首尾的空格
// 8. 刪除首尾空格
console.log(" lili ".trim());
- 字符串的切割
// 9. 字符串的切割split:返回值是一個string類型的數(shù)組
var infos = "aaa-bbb-ccc-ddd"
// 傳入一個分隔符
var items = infos.split("-")
console.log(items);
// join:把數(shù)組轉(zhuǎn)為字符串,參數(shù)為以什么連接
var str3 = items.join("*")
console.log(str3);
- 補(bǔ)齊字符串:str.padStart(4, “0”)
9.7 數(shù)組 Array
- 一系列的商品,使用鍵值對訪問并不方便,需要一個有序的集合,里面的元素是按照某一個順序來排列的,可以通過索引來獲取到它----編程語言提供了一種數(shù)據(jù)結(jié)構(gòu):數(shù)組[]
<body>
<script>
// 1. 創(chuàng)建數(shù)組的方式一:字面量的方式
var names = ["aaa", "bbb", "ccc"]//字符串類型
var products = [
{ name: "iphone", price: 99, desc: "九塊九" },
{ name: "鼠標(biāo)", price: 199, desc: "哈哈" },
{ name: "鍵盤", price: 989, desc: "六點(diǎn)多" },
]//對象類型
// 2. 創(chuàng)建數(shù)組方式二:類Array
var arr1 = new Array()
console.log(arr1);
var arr2 = new Array("abc", "cba", "nba")//["abc","cba","nba"]
console.log(arr2);
// 傳入一個數(shù)字,會默認(rèn)當(dāng)成常見一個對應(yīng)長度的數(shù)組
var arr3 = new Array(5)//[empty * 5]
</script>
</body>
- 數(shù)組的基本操作
<script>
var names = ["aaa", "bbbb", "ccccc"]
// 1. 訪問數(shù)組中的元素
console.log(names[0]);
console.log(names.at(-1));
// 2. 修改數(shù)組中的元素
names[0] = "why"
// 3. 新增數(shù)組中的元素
names[3] = "kobe"//沒有人這么做
// 4. 刪除數(shù)組中的元素
delete names[1]//empty,沒有人這么做
</script>
<script>
var names = ["lili", "dameinb", "jiao"]
// 在數(shù)組的尾部添加和刪除元素
// push方法
names.push("aaaa", "dddd")
// pop方法
names.pop()
// 在數(shù)組的頭部添加和刪除元素:效率非常低
// unshift方法
names.unshift("sss", "hhh")
// shift方法
names.shift()
// splice方法:處理數(shù)組的利器,修改的是原數(shù)組
// 能夠在任意位置添加/刪除/替換元素
// 參數(shù)一:start,從什么位置開始操作函數(shù)
// 參數(shù)二:deleteCount,刪除元素的個數(shù)
// 1. 刪除元素
names.splice(1,2)
// 2. 新增元素:deleteCount=0,后面可以添加新的元素
names.splice(1,0,"why","kebe")
// 3. 替換元素:先移除,再新增
names.splice(1,2,"lisssss","yejie")
</script>
- length 屬性
- length屬性是可寫的,可以擴(kuò)容,但是一般不需要擴(kuò)容
- 清空數(shù)組:arr.length = 0
<script>
var names = ["lilio", "xiaoming", "xiaohong"]
// 獲取數(shù)組的長度
console.log(names.length);
// length屬性可寫的
names.length=10
// 會自動對數(shù)組進(jìn)行擴(kuò)容
// 設(shè)置的length小于原來的元素個數(shù)
names.length = 2//會將后面的內(nèi)容截取掉
</script>
- 數(shù)組的遍歷
// 數(shù)組的遍歷
// 1. 普通的for循環(huán)
for (var i = 0; i < names.length; i++) {
console.log(names[i]);
}
// 2. for in:適用于需要獲取對應(yīng)的索引
for (var index in names) {
console.log(index, names[index]);
}
// 3. for of
for (var item of names) {
console.log(item);
}
- 數(shù)組方法
- slice:對數(shù)組進(jìn)行截取
var names = ["abc","ddd","ggg","ytyt"]
// 1. slice 方法:不會修改原數(shù)組
// 與splice 區(qū)別:splice修改原有的數(shù)組
var newNames = names.slice(1)
console.log(newNames);
- concat:將多個數(shù)組拼接在一起
// 2. concat :將多個數(shù)組拼接在一起
var name1 = "lili"
var name2 = "jiao"
var name3 = "dandan"
// 使用展開運(yùn)算符
const newNames = []
newNames.push(...name1,...name2,...name3)
const newNamess=name1.concat(name2,name3)
console.log(newNamess);
- join:將數(shù)組轉(zhuǎn)成字符串,split:將字符串轉(zhuǎn)化成數(shù)組
// 3. join:將數(shù)組變成字符串
console.log(names.join("-"));
- 查找元素
- indexOf:針對原始類型
// 1. 數(shù)組中存放的是原始類型
var names=["abc","cba","dddd"]
// 1.1 indexOf
// 找到返回索引
// 沒找到返回-1
console.log(names.indexOf('abc'));
// 2. 數(shù)組中存放的是對象類型
var student = [
{id:1002,name:"hey2",age:14},
{id:1004,name:"hey3",age:15},
{id:1005,name:"hey5",age:64},
{id:1006,name:"hey4",age:34},
]
// 查找id為1004的學(xué)生信息
// 2.1 自己寫一個for循環(huán)
// var stu = {}
// 因此初始化為null
var stu =null
// 賦值為空的缺點(diǎn):1. 轉(zhuǎn)為布爾值都是真值 2. 空對象會占用內(nèi)存
for(var i =0;i<student.length;i++){
if(student[i].id === 1004){
console.log(student[i]);
stu = student[i]
break
}
}
// 判斷有沒有找到對應(yīng)的學(xué)生
if(stu){
console.log("找到了");
}
- find 方法
// 2.2 find方法:高階函數(shù):數(shù)組中有幾個元素就會調(diào)用多少次傳入的函數(shù)
var stu = student.find(function (item) {
// console.log(item);
if (item.id === 1004) return true
})
// 簡寫:
var stu = student.find(item => item.id === 1004)
</script>
//手動實(shí)現(xiàn)高階函數(shù)forEach
var names = ["dd", "ddd", "gggg"]
// forEach 函數(shù):可以幫助遍歷數(shù)組
// names.forEach(function (item, index, err) {
// console.log(item, index, err);
// })
// //版本一:回調(diào)函數(shù)
// // 自己實(shí)現(xiàn)上述函數(shù)
// function liliForEach(fn) {
// for (var i = 0; i < names.length; i++) {
// fn(names[i], i, names)
// }
// }
// liliForEach(function (item, index, names) {
// console.log(item, index, names);
// })
// //版本二
// function liliForEach(fn, arr) {
// for (var i = 0; i < arr.length; i++) {
// fn(names[i], i, arr)
// }
// }
// liliForEach(function (item, index, names) {
// console.log(item, index, names);
// }, names)
// // 版本三:往對象里面加屬性
// names.liliForEach = function liliForEach(fn) {
// for (var i = 0; i < this.length; i++) {
// fn(this[i], i, this)
// }
// }
// names.liliForEach(function (item, index, names) {
// console.log(item, index, names);
// })
// 版本四:放在原型鏈上
Array.prototype.liliForEach = function liliForEach(fn) {
for (var i = 0; i < this.length; i++) {
fn(this[i], i, this)
}
}
names.liliForEach(function (item, index, names) {
console.log(item, index, names);
})
//手動實(shí)現(xiàn)高階函數(shù)forEach
// 原始類型
var names = ["abc", "vvv", "ooo1"]
// 內(nèi)部函數(shù)返回true,意味著找到了,后邊就不需要遍歷了,后面的不會繼續(xù)執(zhí)行
// 沒有返回值意味著返回undefined,布爾值為false
names.find(function (item, index, arr) {
console.log(item, index, arr);
// return true//返回了第一個元素而不是true
})
// 數(shù)組中對象類型
var students = [
{ id: 1002, name: "hey2", age: 14 },
{ id: 1004, name: "hey3", age: 15 },
{ id: 1005, name: "hey5", age: 64 },
{ id: 1006, name: "hey4", age: 34 },
]
students.find(function (item) {
console.log(item);
return item.id === 1002
})
// 自己實(shí)現(xiàn)
Array.prototype.liliFind = function (fn) {
var item //可以不設(shè)定,默認(rèn)為undefined
for (var i = 0; i < this.length; i++) {
var isFlag = fn(this[i], i, this)
if (isFlag) {
// item = this[i]
// break
return this[i]
}
}
// return item
}
students.liliFind(function (item, index, arr) {
return item.id === 101
})
- includes:返回 true / false
- findIndex:查找元素的索引,找不到返回 -1
// 查找元素
// indexOf/lastIndexOf
// includes
console.log(names.includes('abc'));
// findIndex:查找元素索引
var findIndex = names.findIndex(function(item,index,arr){
return item === 'nba'
})
console.log(findIndex);
-
數(shù)組的排序:sort修改原數(shù)組
-
數(shù)組的反轉(zhuǎn):reserve生成一個新的數(shù)組
-
其他高階函數(shù)
-
reduce
-
filter
-
map
-
// 1.forEach函數(shù)
var names = ["abc", "cba", "nba", "mba"]
// 三種方式, 新增一種方式
names.forEach(function (item) {
console.log(item)
})
names.forEach(item => console.log(item))
// 2.filter函數(shù): 過濾
var nums = [11, 20, 55, 100, 88, 32]
// 2.1. for循環(huán)實(shí)現(xiàn)
var newNums = []
// for of方法
for (var item of nums) {
if (item % 2 === 0) {
newNums.push(item)
}
}
// 2.2. filter實(shí)現(xiàn):形成新數(shù)組
// 只篩選出滿足條件的
// var newNums = nums.filter(function(item) {
// return item % 2 === 0
// })
// console.log(newNums)
// 3.map函數(shù): 映射:對原來的數(shù)組元素進(jìn)行變化,映射形成新數(shù)組
var nums = [11, 20, 55, 100, 88, 32]
var newNums = nums.map(function (item) {
return item * item
})
console.log(newNums)
// 4.reduce
var numbers = [11, 20, 55, 100, 88, 32]
var result = 0
for (var item of numbers) {
result += item
}
console.log(result)
// initialValue: 初始化值, 第一次執(zhí)行的時候, 對應(yīng)的preValue
// 如果initialValue沒有傳呢?
var result = nums.reduce(function(preValue, item) {
console.log(`preValue:${preValue} item:${item}`)
return preValue + item
}, 0)
console.log(result)
// reduce練習(xí)
var products = [
{ name: "鼠標(biāo)", price: 88, count: 3 },
{ name: "鍵盤", price: 200, count: 2 },
{ name: "耳機(jī)", price: 9.9, count: 10 },
]
var totalPrice = products.reduce(function(preValue, item) {
return preValue + item.price * item.count
}, 0)
console.log(totalPrice)
// 綜合練習(xí):
var nums = [11, 20, 55, 100, 88, 32]
// 過濾所有的偶數(shù), 映射所有偶數(shù)的平方, 并且計算他們的和
var total = nums.filter(function (item) {
return item % 2 === 0
}).map(function (item) {
return item * item
}).reduce(function (preValue, item) {
return preValue + item
}, 0)
console.log(total)
var total = nums.filter(item => item % 2 === 0)
.map(item => item * item)
.reduce((preValue, item) => preValue + item, 0)
console.log(total)
9.8 String 和 Array 常見操作
9.8.1 String 的常見操作
- 創(chuàng)建方式 new String()
- 屬性
- length —獲取字符串的長度
- 訪問其中元素
- [0]
- charAt(0)
- 遍歷
- 普通的for循環(huán)
- for…of方式
- 可迭代對象
- 字符串/數(shù)組
- 字符串不可變性
- 實(shí)例方法:
- toUpperCase() 將所有的字符轉(zhuǎn)成大寫;
- toLowerCase() 將所有的字符轉(zhuǎn)成小寫;
- indexOf 查找字符串位置
- includes 是否包含字符串
- startsWith 判斷是否以xxx開頭
- endsWith 判斷是否以xxx結(jié)尾
- repace 替換字符串
- slice/substring/substr 獲取子字符串
- concat 字符串拼接
- trim 去除首尾空格
- split 字符串分割,字符串—>數(shù)組
- join 數(shù)組–>字符串
9.8.2 Array 的常見操作
-
創(chuàng)建數(shù)組
- [] 數(shù)組字面量
- new Array()
- 傳1個數(shù)組,表示數(shù)組的長度
-
數(shù)組基本操作
- 獲取元素
- [0]
- at(0)
- 修改元素
arr[1] = "fff"
- 新增
arr[5]="123"
- 刪除
delete arr[0]
- 獲取元素
-
在數(shù)組的尾部:
- push 尾部添加
- pop 刪除尾部的最后一個元素,返回被刪除的元素
-
在數(shù)組首部
- unshift 首部添加
- shift 刪除首部的第一個元素,返回被刪除的元素
-
利器
- splice 在任何位置添加/刪除/替換元素
- start 從什么位置開始操作元素
- deleteCount 刪除元素的個數(shù)
- 2 刪除2個
- 0 添加元素
- item1/item2 添加或者替換的元素
- splice 在任何位置添加/刪除/替換元素
9.9 時間的表示
-
UTC :標(biāo)準(zhǔn)的時間
-
創(chuàng)建 Date對象
//創(chuàng)建Date對象的方式
// 1. 沒有傳入任何的參數(shù),獲取到當(dāng)前時間
var date1 = new Date()
console.log(date1);
// 2. 傳入?yún)?shù):時間字符串
var date2 = new Date("2022-09-09")
console.log(date2);
// 3. 傳入具體的年月日時分秒
var date3 = new Date(2023, 10, 10, 9, 8, 7, 333)
console.log(date3);
// 4. 傳入一個 Unix 時間戳==》需要轉(zhuǎn)成對應(yīng)的時間
// 1s ==> 1000ms
var date4 = new Date(100000000000233)
console.log(date4);
- Date 對象的字符串形式:
new Date().toISOSTring()
---- 但其實(shí)也不經(jīng)常用 - 獲取時間信息
// 獲取想要的時間信息
var date = new Date()
console.log(date.toISOString());
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
// 一周中的第幾天
var weekday = data.getDay()
- Date轉(zhuǎn)變?yōu)闀r間戳:
// Date對象如何轉(zhuǎn)成時間戳
var date = new Date()
console.log(date);
// 方法一:當(dāng)前時間的時間戳
var timestamp = Date.now()
console.log(timestamp);
var timestamp1 = date.getTime()//獲取時間戳一
var timestamp2 = date.valueOf()//獲取時間戳二
//計算操作花費(fèi)的時間
var startTime = Date.now()
for (var i = 0; i < 10000; i++) {
console.log(i);
}
var endTime = Date.now()
console.log("花費(fèi)的時間:", endTime - startTime);
十、JavaScript 的 DOM 操作
10.1 DOM 、BOM
-
利用瀏覽器提供給開發(fā)者的DOM、BOM相關(guān)的API才能對頁面、瀏覽器進(jìn)行操作
-
API:application programming interface
-
DOM:文檔對象模型
- 瀏覽器將其抽取為一個個文檔對象模型
- 將網(wǎng)頁里面的所有內(nèi)容表示為可以修改的對象
- 通過 api 去獲取
- 整個的文檔為 document
- js 語法和瀏覽器之間的橋梁
- 這些對象都可以通過JavaScript來對其進(jìn)行訪問
-
BOM:瀏覽器對象模型
- 瀏覽器提供的用于處理文檔之外的所有內(nèi)容的其他對象
- navigator、location、history
10.2 DOM
-
DOM tree:抽象成DOM對象的時候,會形成一個樹結(jié)構(gòu)
-
學(xué)習(xí)順序
- DOM元素之間的關(guān)系
- 獲取DOM元素
- DOM節(jié)點(diǎn)的 type、tag、content
- DOM 節(jié)點(diǎn)的attributes、properies
- DOM 節(jié)點(diǎn)的創(chuàng)建、插入、克隆、刪除
- DOM 節(jié)點(diǎn)的樣式、類
- DOM 元素/window的大小、滾動、坐標(biāo)
-
繼承關(guān)系圖
10.3 document 對象
- document 節(jié)點(diǎn)表示的是整個載入的網(wǎng)頁,它的實(shí)例是全局的 document 對象
- 是DOM的入口點(diǎn),可以從document開始去訪問任何節(jié)點(diǎn)元素
- 對于最頂層的 html、head、body 元素可以直接在 document 對象中獲取到:
- html元素: = document.documentElement
- body元素: = document.body
- head元素: = document.head
- 文檔聲明: = document.doctype
10.4 DOM 和 document 對象
- DOM:
文檔對象模型(Document Object Model)將頁面所有的內(nèi)容表示為可以修改的對象
- 瀏覽器將編寫在HTML中的每一個元素(Element)都抽象成了一個個對象
- 所有這些對象都可以通過JavaScript來對其進(jìn)行訪問,可以通過 JavaScript來操作頁面;
- 將這個抽象過程稱之為 文檔對象模型(Document Object Model)
- Document節(jié)點(diǎn)表示的整個載入的網(wǎng)頁,它的實(shí)例是全局的document對象:
對DOM的所有操作都是從 document 對象開始的
- 它是DOM的入口點(diǎn),可以從document開始去訪問任何節(jié)點(diǎn)元素;
10.5 節(jié)點(diǎn)之間的導(dǎo)航
- 父節(jié)點(diǎn):parentNode
- 前兄弟節(jié)點(diǎn):previousSibling
- 后兄弟節(jié)點(diǎn):nextSibling
- 子節(jié)點(diǎn):childNodes
- 第一個子節(jié)點(diǎn):firstChild
- 第二個子節(jié)點(diǎn):lastChild
10.6 元素之間的導(dǎo)航
- 獲取到一個元素后,根據(jù)這個元素去獲取其他的元素
- 父元素:parentElement
- 前兄弟節(jié)點(diǎn):previousElementSibling
- 后兄弟節(jié)點(diǎn):nextElementSibling
- 子節(jié)點(diǎn):children
- 第一個子節(jié)點(diǎn):firstElementChild
- 第二個子節(jié)點(diǎn):lastElementChild
10.7 表格元素的導(dǎo)航
- 元素獨(dú)特屬性:
- table.rows —
- table.caption/tHead/tFoot — 引用元素
- ,
- table.tBodies —
- 元素的集合;
, -
,, 元素提供了 rows 屬性:
- tbody.rows — 表格內(nèi)部 元素的集合
-
- tr.cells — 在給定 中的 和 單元格的集合;
- tr.sectionRowIndex — 給定的 在封閉的 // 中的位置(索引);
- tr.rowIndex — 在整個表格中 的編號(包括表格的所有行)
-
和
- td.cellIndex — 在封閉的 中單元格的編號
10.8 表單元素的導(dǎo)航
- 通過document來獲?。篸ocument.forms
- 獲取form元素中的內(nèi)容:form.elements
- 設(shè)置表單子元素的name來獲取他們
- elements.accounts.value
10.9 獲取元素
- 通過導(dǎo)航獲?。阂粚右粚幽媚硞€單獨(dú)的元素非常不方便,當(dāng)元素彼此靠近豁這相鄰時候,導(dǎo)航屬性非常有用
- 直接獲?。?
- document.getElementsByClassName(“keyword”)
- document.getElementById(‘title’)
- querySelector 和 querySelectAll
// 1. 元素之間的導(dǎo)航
// 1. 拿到 body
var bodyEl = document.body
// 2. 拿到 box
var boxEl = bodyEl.firstElementChild
// 3. 拿到 container
var containerEl = boxEl.children[1]
// 4. 拿到 p
var pEl = containerEl.children[0]
// 5. 拿到 keyword
var spanEl = pEl.children[0]
spanEl.style.color = 'red'
// 2 通過getElementBy直接獲取
// 2.1 通過classname獲取火速
var keyword = document.getElementsByClassName("keyword")
// 2.2 通過id獲取元素
var titleEl = document.getElementById('title')
// 3 通過選擇器查詢
var keyWordEL = document.querySelector('.keyword')
var keywordEls = document.querySelectorAll('.keyword')
// 是類數(shù)組對象但是是可迭代的,支持for of,有一個索引屬性,不是數(shù)組
//可迭代對象:String,數(shù)組,節(jié)點(diǎn)列表
10.10 節(jié)點(diǎn)的屬性-nodeType
-
nodeType:節(jié)點(diǎn)的類型
- 數(shù)值類型:
- 10:DocumentType 節(jié)
- 9:Document
- 8:注釋
- 3:文字
- 1:元素
-
nodeName:針對于節(jié)點(diǎn),節(jié)點(diǎn)的名稱
-
tagName:針對于元素,元素的標(biāo)簽名稱
-
data/nodeValue:針對非元素的節(jié)點(diǎn)獲取數(shù)據(jù)
-
innerHTML:對應(yīng)的html元素也會獲取,會直接進(jìn)行替換,能夠識別標(biāo)簽
-
textContent:只會獲取文本內(nèi)容,不能夠識別標(biāo)簽
-
outerHTML
-
hidden屬性:也是一個全局屬性,可以用于設(shè)置元素隱藏,display
-
總結(jié)
- nodeName:獲取node節(jié)點(diǎn)的名字
- tagName:獲取元素的標(biāo)簽名詞
- innerHTML:將元素中的 HTML 獲取為字符串形式;設(shè)置元素中的內(nèi)容
- outerHTML:包含了元素的完整 HTML;innerHTML 加上元素本身
- textContent:僅僅獲取元素中的文本內(nèi)容
- nodeValue:用于獲取非元素節(jié)點(diǎn)的文本內(nèi)容
- hidden:可以用于設(shè)置元素隱藏
10.11 元素的特性 attribute
- 分類
- 標(biāo)準(zhǔn):html標(biāo)準(zhǔn)中原有的
- 非標(biāo)準(zhǔn):自定義的
- 操作
- elem**.hasAttribute(name) — 檢查特性是否存在**。
- elem.getAttribute(name) — 獲取這個特性值,拿到字符串。
- elem.setAttribute(name, value) — 設(shè)置這個特性值。
- elem.removeAttribute(name) — 移除這個特性。
- attributes:attr 對象的集合,具有name、value屬性;
10.12 元素的屬性 property
- 對于標(biāo)準(zhǔn)的 attribute,會在DOM對象上創(chuàng)建與其對應(yīng)的 property 屬性:標(biāo)準(zhǔn)的attribute都有對應(yīng)的 property
-
在大多數(shù)情況下,它們是相互作用的
- 改變property,通過attribute獲取的值,會隨著改變;
- 通過attribute操作修改,property的值會隨著改變;
- 如果不支持就使用 setAttribute (比較標(biāo)準(zhǔn))
10.13 動態(tài)修改樣式
- 選擇一:在 CSS 中 編寫好對應(yīng)的樣式,動態(tài)的添加 class
- 比較固定的值
boxEl.className = 'active'
- 選擇二:動態(tài)的修改style屬性;
- 精準(zhǔn)的修改
boxEl.style.color = 'red'
boxEl.style.fontSize = '24px'
10.14 元素的 className 和 classList
- 在 attribute 中對應(yīng)為 class,對應(yīng)的 property 為 className
- className 會進(jìn)行覆蓋
-
添加或者移除單個的class,那么可以使用classList屬性,不會覆蓋掉其他的
- elem.classList 是一個特殊的對象
- elem.classList.add (class) :添加一個類
- elem.classList.remove(class):添加/移除類
- elem.classList.toggle(class) :如果類不存在就添加類,存在就移除
- elem.classList.contains(class):檢查給定類,返回 true/false。
- classList是可迭代對象,可以通過for of進(jìn)行遍歷
- elem.classList 是一個特殊的對象
## 10.15 元素的 style 屬性
- 單獨(dú)修改某一個 CSS 屬性,那么可以通過 style 來操作:
- 對于多詞(multi-word)屬性,使用駝峰式 camelCase
- 將值設(shè)置為空字符串,那么會使用 CSS 的默認(rèn)樣式
- 多個樣式需要使用 cssText 屬性
10.16 元素 style 的讀取 - getComputedStyle
- 對于內(nèi)聯(lián)樣式,是可以通過style.*的方式讀取到的
- 對于 style、css 文件中的樣式,是讀取不到的
- getComputedStyle 的全局函數(shù)來實(shí)現(xiàn):getComputedStyle(boxEl).fontSize
10.17 data-自定義屬性
- HTML5 新增
- 如果直接寫的話就是 attributes 添加了一個 age 屬性,不推薦這種寫法
- 推薦使用 data-*自定義屬性
- 標(biāo)簽中自定義:
data-age = '19'
- 在 script 中獲取:
boxEl.dataset.age
10.18 創(chuàng)建元素
-
插入一個元素
-
早期使用 document.write 方法寫入
-
后期
- 步驟一:創(chuàng)建一個元素:document.createElement(tag)
// 真實(shí)地創(chuàng)建一個 DOM 對象 var h2El = document.createElement("h2") h2El.textContent = '我是標(biāo)題'
- 步驟二:插入元素到DOM的某一個位置;
// 將元素加入boxboxEl boxEl.append(h2El)
-
10.19 插入元素
- node.append(…nodes or strings) —— 在 node 末尾 插入節(jié)點(diǎn)或字符串
- node.prepend(…nodes or strings) —— 在 node 開頭 插入節(jié)點(diǎn)或字符串
- node.before(…nodes or strings) —— 在 node 前面 插入節(jié)點(diǎn)或字符串
- node.after(…nodes or strings) —— 在 node 后面 插入節(jié)點(diǎn)或字符串
- node.replaceWith(…nodes or strings) —— 將 node 替換為給定的節(jié)點(diǎn)或字符串
10.20 移除和克隆元素
- 調(diào)用元素本身的 remove 方法
-
復(fù)制一個現(xiàn)有的元素,可以通過 cloneNode 方法
- 可以傳入一個Boolean類型的值,來決定是否是深度克隆
- 深度克隆會克隆對應(yīng)元素的子元素,否則不會
10.21 元素的大小、滾動
-
clientWidth:contentWith+padding(不包含滾動條)內(nèi)容的寬度加上 padding
-
clientHeight:contentHeight+padding
-
clientTop:border-top的寬度
-
clientLeft:border-left的寬度
-
offsetWidth:元素完整的寬度
-
offsetHeight:元素完整的高度
-
offsetLeft:距離父元素的x
-
offsetHeight:距離父元素的y
-
scrollHeight:整個可滾動的區(qū)域高度
-
scrollTop:滾動部分的高度
10.22 window 的大小、滾動
- **window 的 width 和 height **
- innerWidth、innerHeight:獲取window窗口的寬度和高度(包含滾動條)
- outerWidth、outerHeight:獲取window窗口的整個寬度和高度(包括調(diào)試工具、工具欄)
- documentElement.clientHeight、documentElement.clientWidth:獲取html的寬度和高度(不包含滾動條)
-
window 的滾動位置:
- scrollX:X軸滾動的位置(別名pageXOffset)
- scrollY:Y軸滾動的位置(別名pageYOffset)
-
也有提供對應(yīng)的滾動方法:
- scrollBy(x,y) :將頁面滾動至 相對于當(dāng)前位置的 (x, y) 位置:
scrollBy(0,100)
- 方法 scrollTo ( pageX,pageY ) 將頁面滾動至 絕對坐標(biāo);
- scrollBy(x,y) :將頁面滾動至 相對于當(dāng)前位置的 (x, y) 位置:
10.23 動態(tài)創(chuàng)建列表
<body>
<ul class="list">
</ul>
<script>
var ulEl = document.querySelector('.list')
var isFlag = true
while (isFlag) {
var message = prompt('請輸入待處理事件')
if (!message) {
isFlag = false
} else {
var liEl = document.createElement('li')
liEl.textContent = message
ulEl.append(liEl)
}
}
</script>
</body>
10.24 倒計時
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.countdown {
color: red;
font-size: 40px;
}
.countdown .time {
background-color: rgb(187, 119, 31);
color: azure;
display: inline-block;
padding: 50px;
border-radius: 3px;
}
</style>
</head>
<body>
<div class="countdown">
<span class="time hour">03</span>
<span class="split">:</span>
<span class="time minute">03</span>
<span class="split">:</span>
<span class="time second">03</span>
</div>
<script>
// 1. 獲取元素
var hourElement = document.querySelector('.hour')
var minuteElement = document.querySelector('.minute')
var secondElement = document.querySelector('.second')
setInterval(function(){
// 2. 獲取倒計時的時間
var nowDate = new Date()
var endDate = new Date()
endDate.setHours(24)
endDate.setMinutes(24)
endDate.setSeconds(24)
endDate.setMilliseconds(24)
// 間隔時間
var interValTime = Math.floor((endDate.getTime() - nowDate.getTime()) / 1000)
// 秒 ==》 小時 分鐘 秒鐘 按照六十進(jìn)制
var hour = Math.floor(interValTime / 3600)
var minute = Math.floor((interValTime / 60) % 60)
var second = interValTime % 60
// 3. 設(shè)置內(nèi)容
hourElement.textContent = padLeft(hour)
minuteElement.textContent = padLeft(minute)
secondElement.textContent = padLeft(second)
},1000)
function padLeft(content, count, padStr) {
count = count | 2
padStr = padStr | '0'
content = String(content)
return content.padStart(count, padStr)
}
</script>
</body>
</html>
十一、JavaScript的事件處理
11.1 事件(Event)
-
Web頁面需要經(jīng)常和用戶之間進(jìn)行交互,而交互的過程中可能想要捕捉這個交互的過程
- 比如用戶點(diǎn)擊了某個按鈕、用戶在輸入框里面輸入了某個文本、用戶鼠標(biāo)經(jīng)過了某個位置
- 瀏覽器需要搭建一條JavaScript代碼和事件之間的橋梁,瀏覽器進(jìn)行調(diào)用
- 當(dāng)某個事件發(fā)生時,讓JavaScript可以相應(yīng)(執(zhí)行某個函數(shù)),所以需要針對事件編寫處理程序(handler)
-
事件監(jiān)聽
- 事件監(jiān)聽方式一:在script中直接監(jiān)聽(很少使用)
- js 代碼和 html 代碼混合
- 事件監(jiān)聽方式二:DOM 屬性,通過元素的on來監(jiān)聽事件
- 獲取元素對象,onclick屬性
- 不能調(diào)用多個函數(shù),只有最后的函數(shù)會生效
-
事件監(jiān)聽方式三:通過 EventTarget 中的 addEventListener 來監(jiān)聽
- 獲取元素對象
- btnEl.addEventListener (“click”,fn1)
- 事件監(jiān)聽方式一:在script中直接監(jiān)聽(很少使用)
11.2 事件冒泡和事件捕獲
- 事件冒泡:默認(rèn)情況下事件是從最內(nèi)層的span向外依次傳遞的順序
- 事件捕獲:從外層到內(nèi)層(body -> span)
-
如果都監(jiān)聽,那么會按照如下順序來執(zhí)行:
- 捕獲階段(Capturing phase):事件(從 Window)向下走近元素
- 目標(biāo)階段(Target phase):事件到達(dá)目標(biāo)元素
- 冒泡階段(Bubbling phase):事件從元素上開始冒泡
-
事實(shí)上,可以通過event對象來獲取當(dāng)前的階段:
- eventPhase
- 開發(fā)中通常會使用事件冒泡
## 11.3 事件對象
- 當(dāng)一個事件發(fā)生時,就會有和這個事件相關(guān)的很多信息
- 比如事件的類型是什么,點(diǎn)擊的是哪一個元素,點(diǎn)擊的位置是哪里等等相關(guān)的信息
- 那么這些信息會被封裝到一個Event對象中,這個對象由瀏覽器創(chuàng)建,稱之為event對象
- 該對象提供了想要的一些屬性,以及可以通過該對象進(jìn)行某些操作
- 獲取這個 event 對象
- event 對象會在傳入的事件處理(event handler)函數(shù)回調(diào)時,被系統(tǒng)傳入
- 可以在回調(diào)函數(shù)中拿到這個event對象
## 11.4 event 常見的屬性和方法
-
常見的屬性
- type:事件的類型
- target:當(dāng)前事件發(fā)生的元素
-
currentTarget:當(dāng)前處理事件的元素(父元素)
- 事件冒泡會有區(qū)別
- eventPhase:事件所處的階段
- 捕獲:1
- 目標(biāo):2
- 冒泡:3
- offsetX、offsetY:事件發(fā)生在元素內(nèi)的位置
- clientX、clientY:事件發(fā)生在客戶端內(nèi)的位置(可見的視口)
- pageX、pageY:事件發(fā)生在客戶端相對于document的位置(文檔)
- screenX、screenY:事件發(fā)生相對于屏幕的位置
-
常見的方法
- preventDefault:取消事件的默認(rèn)行為
var aEl = document.querySelector("a") aEl.onclick = function(event){ event.preventDefault() }
- stopPropagation:阻止事件的進(jìn)一步傳遞(冒泡或者捕獲都可以阻止)
11.5 事件處理中的this
- this指向誰跟瀏覽器怎么調(diào)用有關(guān)
- 綁定到誰身上就是指向誰
- 綁定到處理的元素
currentTarget
11.6 EventTarget類
-
所有的節(jié)點(diǎn)、元素都繼承自EventTarget
- Window也繼承自EventTarget
-
EventTarget
- EventTarget是一個DOM接口,主要用于添加、刪除、派發(fā)Event事件
- 可以實(shí)現(xiàn)類似于事件總線的效果
-
EventTarget常見的方法
- addEventListener:注冊某個事件類型以及事件處理函數(shù)
- removeEventListener:移除某個事件類型以及事件處理函數(shù)
- 移除要移除之前對應(yīng)加進(jìn)去的函數(shù)
- dispatchEvent:派發(fā)某個事件類型到 EventTarget 上
11.7 事件委托
- 利用事件的冒泡機(jī)制,以及事件對象中可以準(zhǔn)確獲知觸發(fā)事件的元素機(jī)制(e.target),將子元素事件委托給父元素處理的現(xiàn)象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.active {
color: red;
font-size: 20px;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>0</li>
</ul>
<script>
// 1.每一個li都監(jiān)聽自己的點(diǎn)擊,并且有自己的處理函數(shù)
var liEls = document.querySelectorAll("li")
for (const liEl of liEls) {
liEl.onclick = function (event) {
event.currentTarget.classList.add('active')
console.log("點(diǎn)擊li");
}
}
// 2. 統(tǒng)一在ul中進(jìn)行監(jiān)聽
var ulEl = document.querySelector("ul")
ulEl.onclick = function (event) {
event.target.classList.add('active')
console.log("點(diǎn)擊li");
}
// 3. 點(diǎn)擊li變成active,其他取消active
var ulEl = document.querySelector("ul")
// 3.1 變量記錄的方式
var activeLiEl = null
ulEl.onclick = function (event) {
// 邊界判斷
if (activeLiEl && event.target !== ulEl) {
activeLiEl.classList.remove("active")
}
// 3.2 給點(diǎn)擊的元素添加active
if (event.target !== ulEl) {
event.target.classList.add('active')
}
console.log("點(diǎn)擊li");
// 3.3 記錄最新的active對應(yīng)的li
activeLiEl = event.target
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box">
<button data-action="remove">移除</button>
<button data-action="new">新建</button>
<button data-action="search">搜索</button>
</div>
<script>
var boxEl = document.querySelector(".box")
boxEl.onclick = function (event) {
var btnEl = event.target
var action = btnEl.dataset.action
switch (action) {
case "remove":
console.log("click remove");
break
case "new":
console.log("click new");
break
case "search":
console.log("click search");
break
}
}
</script>
</body>
</html>
11.8 常見的鼠標(biāo)事件
- click:當(dāng)用戶點(diǎn)擊某個對象時調(diào)用的事件
- contextmenu:在用戶點(diǎn)擊鼠標(biāo)右鍵打開上下文菜單時觸發(fā)
- dblclick:當(dāng)用戶雙擊某個對象時調(diào)用的事件
- mousedown :鼠標(biāo)按鈕被按下
- mouseup:鼠標(biāo)按鍵被松開
- mousemove :鼠標(biāo)被移動
- mouseover :鼠標(biāo)移到某元素之上(支持冒泡)
- mouseout :鼠標(biāo)從某元素移開(支持冒泡)
- mouseenter :當(dāng)鼠標(biāo)指針移動到元素上時觸發(fā)(不支持冒泡)
- mouseleave :當(dāng)鼠標(biāo)指針移出元素時觸發(fā)(不支持冒泡)
11.9 mouseover 和 mouseenter 的區(qū)別
-
mouseenter 和 mouseleave
- 不支持冒泡
- 進(jìn)入子元素依然屬于在該元素內(nèi),沒有任何反應(yīng)
-
mouseover和mouseout
- 支持冒泡
- 進(jìn)入元素的子元素時
- 先調(diào)用父元素的mouseout
- 再調(diào)用子元素的mouseover
- 因為支持冒泡,所以會將mouseover傳遞到父元素中
- 應(yīng)用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
display: flex;
width: 300px;
height: 300px;
background-color: aquamarine;
}
button {
flex: 1;
height: 40px;
}
</style>
</head>
<body>
<div class="box">
<button>刪除</button>
<button>新增</button>
<button>搜索</button>
</div>
<script>
// 方案一:監(jiān)聽的本身就是button元素
// var btnEls = document.querySelectorAll('button')
// for (var i = 0; i < btnEls.length; i++) {
// btnEls[i].onmouseenter = function (event) {
// console.log(event.target.textContent);
// }
// }
// 方案二:事件委托(只給父元素綁定一個元素)
var boxEl = document.querySelector(".box")
boxEl.onmouseover = function (event) {
if (event.target.tagName === 'BUTTON')
console.log(event.target.textContent);
}
</script>
</body>
</html>
11.10 常見的鍵盤事件
-
onkeydown :某個鍵盤按鍵被按下,down事件先發(fā)生
-
onkeypress :某個鍵盤按鍵被按下,press 發(fā)生在文本被輸入
-
onkeyup :某個鍵盤按鍵被松開,up發(fā)生在文本輸入完成
-
可以通過 key 和 code 來區(qū)分按下的鍵
- event.code:“按鍵代碼”(
“KeyA”,“ArrowLeft” 等),特定于鍵盤上按鍵的物理位置,不區(qū)分大小寫
- event.key:字符(“A”,“a” 等),對于非字符(non-character)的按鍵,通常具有與 code 相同的值
- keyCode 已經(jīng)遺棄
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text">
<button>button</button>
</body>
<script>
const btnEl = document.querySelector('button')
const inputEl = document.querySelector('input')
btnEl.onclick = function () {
console.log("sousuo");
}
btnEl.onkeyup = function (event) {
if (event.code == 'Enter') {
console.log("search");
}
}
// 按下s,搜索自動獲取焦點(diǎn)
document.onkeyup = function (event) {
console.log("document鍵盤事件", event.key, event.code);
if (event.code === 'KeyS') {
inputEl.focus()
}
}
</script>
</html>
11.11 常見的表單事件
-
onchange 該事件在表單元素的內(nèi)容改變時觸發(fā)( <input>, , , 和 )
-
oninput :元素獲取用戶輸入時觸發(fā)
-
onfocus :元素獲取焦點(diǎn)時觸發(fā)
-
onblur :元素失去焦點(diǎn)時觸發(fā)
-
onreset :表單重置時觸發(fā)
-
onsubmit :表單提交時觸發(fā)
11.12 文檔加載事件
- DOMContentLoaded:瀏覽器已完全加載 HTML,并構(gòu)建了 DOM 樹,但像 和樣式表之類的外部資源可能尚未加載完成
- load:瀏覽器不僅加載完成了 HTML,還加載完成了所有外部資源:圖片,樣式等
十二、DOM 相關(guān)
12.1 window 定時器方法
- 計劃調(diào)用:并不想立即執(zhí)行一個函數(shù),而是等待特定一段時間之后再執(zhí)行
- setTimeout 允許將函數(shù)推遲到一段時間間隔之后再執(zhí)行
- setInterval 允許重復(fù)運(yùn)行一個函數(shù),從一段時間間隔之后開始運(yùn)行,之后以該時間間隔連續(xù)重復(fù)運(yùn)行該函數(shù)
- clearTimeout:取消setTimeout的定時器
- clearInterval:取消setInterval的定時器
12.2 setTimeout 的使用
-
setTimeout的語法如下
- func|code:想要執(zhí)行的函數(shù)或代碼字符串。
- 一般傳入的都是函數(shù),由于某些歷史原因,支持傳入代碼字符串,但是不建議這樣做
- delay:執(zhí)行前的延時,以毫秒為單位(1000 毫秒 = 1 秒),默認(rèn)值是 0
- arg1,arg2…:要傳入被執(zhí)行函數(shù)(或代碼字符串)的參數(shù)列表
- func|code:想要執(zhí)行的函數(shù)或代碼字符串。
-
clearTimeout方法
- setTimeout 在調(diào)用時會返回一個“定時器標(biāo)識符(timer identifier)”,可以使用它來取消執(zhí)行
12.3 setInterval的使用
-
setInterval 方法和 setTimeout 的語法相同
- 所有參數(shù)的意義也是相同的
- 不過與 setTimeout 只執(zhí)行一次不同,setInterval 是每間隔給定的時間周期性執(zhí)行
-
clearInterval方法
- etInterval也會返回一個“定時器標(biāo)識符(timer identifier)”,可以通過clearInterval來取消這個定時器
十三、BOM
13.1 認(rèn)識 BOM
- BOM:瀏覽器對象模型
- 由瀏覽器提供的用于處理文檔之外的所有內(nèi)容的其他對象
- navigator、location、history
- js 有一個非常重要的運(yùn)行環(huán)境就是瀏覽器
- BOM是鏈接js腳本與瀏覽器窗口的橋梁
- BOM 主要包括以下對象模型
- window
- location
- history
- navigator
- screen
13.2 window 對象
- 全局對象
- Node :global
- 瀏覽器:window 對象
- 瀏覽器窗口對象
- 放在 window 對象上的所有屬性都可以被訪問
- 使用 var 定義的變量會被添加到window對象中
- 默認(rèn)提供了全局的函數(shù)和類:setTimeout、Math、Date、Object
- 作用
- 包含大量的屬性:console、location、history、localStorage(60+)
- 包含大量的方法:alert、close、scrollTo、open(40+)
- 包含大量的事件:focus、blur、load、hashchange(30+)
- 包含大量從EventTarget繼承過來的方法
13.3 location 對象
- 用于表示 window 上當(dāng)前鏈接到的 URL 信息
- 常見的屬性
// 完整的URL
console.log(location.href);
// 獲取URL信息
console.log(location.hostname);
console.log(location.host);
console.log(location.protocol);
console.log(location.pathname);
console.log(location.search);
console.log(location.hash);
- 常見的方法
- assign:賦值一個新的URL,并且跳轉(zhuǎn)到新的URL 上
- replace:替換,新的網(wǎng)頁替換原來的網(wǎng)頁
- reload:重新加載這個網(wǎng)頁
13.4 URLSearchParams
- get方法:獲取參數(shù)的值
- set方法:設(shè)置一個搜索參數(shù)和值
- append:追加一個搜索參數(shù)和值
- has:判斷是否有某個搜索參數(shù)
- 中文會進(jìn)行編碼
13.5 history
- 前端路由的核心:修改 url ,但是頁面不刷新
- 修改 hash 值
- 修改 history
- 屬性
- history.length
- history.state
- 方法
- 添加新的歷史:pushState(state,“,”/lili")
- 返回歷史:back()
- 前進(jìn)歷史:forward()
- 跳轉(zhuǎn)層級:go(number)
- 替換歷史:replaceState()
13.6 navigator
- 表示用戶代理的狀態(tài)和標(biāo)識等信息
- 屬性
- userAgent
- vendor
13.7 screen
- 獲取屏幕對應(yīng)的像素
十四、JSON
14.1 認(rèn)識 Json
-
是一種非常重要的數(shù)據(jù)格式,并不是編程語言,可以在服務(wù)器和客戶端之間傳遞
- 服務(wù)器基本上是以 json 格式給你數(shù)據(jù)
- 基本上傳遞都是 json
-
全稱是 JavaScript Object Notation( js 對象符號)
-
一種輕量級資料交換格式,算是 js 的一個子集
-
目前已經(jīng)獨(dú)立于編程呢個語言,可以在各個編程語言中使用
-
在 js 中可以直接使用
-
其他數(shù)據(jù)交換格式,使用什么數(shù)據(jù)格式是一種架構(gòu)
- XML:在解析、傳輸?shù)确矫嫒跤?JSON
-
Protobuf:有可能替換 json
- 即時通信
-
應(yīng)用場景
- 網(wǎng)絡(luò)數(shù)據(jù)的傳輸JSON 數(shù)據(jù)
- 項目的某些配置文件
- 非關(guān)系型數(shù)據(jù)庫 NoSQL 將 json 作為存儲格式
14.2 JSON 基本語法
- 不能在 json 文件中寫注釋
- 數(shù)據(jù)格式(雙引號,不支持單引號)
- 簡單值
- 數(shù)組
- 對象
14.3 JSON 的序列化和反序列化
-
希望將一個對象保存在 localStorage 中,如果直接將對象塞到里面去只能看到 object
-
需要進(jìn)行序列化JSON.stringify():將 obj 對象轉(zhuǎn)成字符串再塞進(jìn)來文章來源:http://www.zghlxwxcb.cn/news/detail-811534.html
- 在轉(zhuǎn)換的過程當(dāng)中改值:replacer
JSON.stringify(obj,function(key,value){if(key==="lili" return "miao")})
- space:轉(zhuǎn)換輸出格式,前面留幾個空格
- 自定義toJSON方法
-
需要進(jìn)行反序列化JSON.parse():將字符串轉(zhuǎn)成 obj 對象拿到結(jié)果文章來源地址http://www.zghlxwxcb.cn/news/detail-811534.html
- 在解析的過程中進(jìn)行修改
JSON.parse(item,function(key,value){if(key==="age")return value+2})
var obj = { name: "lili", age: 99 } // 1. 將 obj 對象進(jìn)行序列化 var objJSONString = JSON.stringify(obj) // 2. 將對象存儲到LocalStorage localStorage.setItem("info", objJSONString) console.log(localStorage.getItem("info")); var item = localStorage.getItem("info") // 3. 將字符串轉(zhuǎn)回對象(反序列化) var newObj = JSON.parse(item)
-
到了這里,關(guān)于循序漸進(jìn)學(xué) JavaScript <二>的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!