零、文章目錄
JavaScript高級二、構(gòu)造函數(shù)&常用函數(shù)
1、深入對象
(1)創(chuàng)建對象三種方式
-
利用對象字面量創(chuàng)建對象
-
利用 new Object 創(chuàng)建對象
-
利用構(gòu)造函數(shù)創(chuàng)建對象
案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>創(chuàng)建對象</title>
</head>
<body>
<script>
//1.對象字面量創(chuàng)建對象
const o1 = {
name: 'zhangsan'
}
console.log(o1)
//2.new Object()創(chuàng)建對象,再屬性賦值
const o2 = new Object()
o2.uname = 'lisi'
console.log(o2)
//new Object()創(chuàng)建對象直接傳入屬性值
const o3 = new Object({
uname: 'wangwu'
})
console.log(o3)
</script>
</body>
</html>
(2)構(gòu)造函數(shù)
-
**構(gòu)造函數(shù) :**是一種特殊的函數(shù),主要用來
快速初始化
類似的對象
-
構(gòu)造函數(shù)語法
- 使用
new
關(guān)鍵字調(diào)用函數(shù)的行為被稱為實例化
- 實例化構(gòu)造函數(shù)時沒有參數(shù)時可以省略 ()
- 構(gòu)造函數(shù)
內(nèi)部無需寫return
,返回值即為新創(chuàng)建的對象,構(gòu)造函數(shù)內(nèi)部的return
返回的值無效 - 命名以
大寫
字母開頭
- 使用
-
實例化執(zhí)行過程
- 創(chuàng)建新對象
- 構(gòu)造函數(shù)this指向新對象
- 執(zhí)行構(gòu)造函數(shù)代碼,修改this,添加新的屬性
- 返回新對象
案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>自定義構(gòu)造函數(shù)</title>
</head>
<body>
<script>
// 創(chuàng)建一個構(gòu)造函數(shù)
function Goods(name, price, count) {
this.name = name
this.price = price
this.count = count
this.sayhi = function() {}
}
//使用構(gòu)造函數(shù)創(chuàng)建對象
const mi = new Goods('小米', 1999, 20)
console.log(mi)
const hw = new Goods('華為', 3999, 59)
console.log(hw)
</script>
</body>
</html>
(3)實例成員&靜態(tài)成員
-
**實例成員:**通過構(gòu)造函數(shù)創(chuàng)建的對象稱為實例對象,
實例對象中的屬性和方法稱為實例成員
。構(gòu)造函數(shù)創(chuàng)建的實例對象彼此獨立互不影響。 -
**靜態(tài)成員:**在 JavaScript 中函數(shù)底層本質(zhì)上也是對象類型,因此允許直接為函數(shù)動態(tài)添加屬性或方法,
構(gòu)造函數(shù)的屬性和方法被稱為靜態(tài)成員
, 一般公共特征
的屬性或方法設(shè)置為靜態(tài)成員,靜態(tài)成員方法中的this 指向構(gòu)造函數(shù)本身
。
案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>實例成員靜態(tài)成員</title>
</head>
<body>
<script>
// 創(chuàng)建一個構(gòu)造函數(shù)
function Goods(name, price, count) {
this.name = name
this.price = price
this.count = count
this.sayhi = function() {}
}
//使用構(gòu)造函數(shù)創(chuàng)建對象
const mi = new Goods('小米', 1999, 20)
console.log(mi)
const hw = new Goods('華為', 3999, 59)
console.log(hw)
//實例成員,只改當(dāng)前實例成員中的數(shù)據(jù)
mi.name = 'vivo'
console.log(mi)
console.log(hw)
// 靜態(tài)成員,修改的數(shù)據(jù)在所有實例間生效
Goods.num = 10
console.log(Goods.num) //10
console.log(mi) //構(gòu)造函數(shù)中包含num
console.log(hw) //構(gòu)造函數(shù)中包含num
</script>
</body>
</html>
2、內(nèi)置構(gòu)造函數(shù)
(1)包裝類型
-
在 JavaScript 中最主要的數(shù)據(jù)類型有 6 種:
- **基本數(shù)據(jù)類型:**字符串、數(shù)值、布爾、undefined、null
- 引用類型: 對象
-
**包裝類型:**字符串、數(shù)值、布爾、等基本類型也都有專門的構(gòu)造函數(shù),就叫包裝類型,我們平時直接賦值,具有對像的使用特征,實際上是js
底層
幫我們調(diào)用了構(gòu)造函數(shù)
,實際上就是個對象。 -
內(nèi)置構(gòu)造函數(shù)
- 引用類型:Object,Array,RegExp,Date 等
- 包裝類型:String,Number,Boolean 等
案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>基本包裝類型</title>
</head>
<body>
<script>
// 平時直接賦值,具有對像的使用特征
// const str = 'pink'
// console.log(str.length)
// 實際js底層完成了構(gòu)造函數(shù)的調(diào)用
const str = new String('pink')
</script>
</body>
</html>
(2)Object
-
Object
是內(nèi)置的構(gòu)造函數(shù),用于創(chuàng)建普通對象。推薦使用字面量方式聲明對象
,而不是Object
構(gòu)造函數(shù)。 -
Object.keys
獲取對象中所有屬性(鍵),返回的是一個數(shù)組 -
Object.values
獲取對象中所有屬性值,返回的是一個數(shù)組 -
Object. assign
常用于對象拷貝,經(jīng)常使用的場景給對象添加屬性
案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object靜態(tài)方法</title>
</head>
<body>
<script>
// 1.構(gòu)造函數(shù)創(chuàng)建對象
// const o = new Object({
// uname: 'pink',
// age: 18
// })
// 1.字面量方式聲明對象,推薦
const o = {
uname: 'pink',
age: 18
}
// 2.獲得所有的屬性名
console.log(Object.keys(o)) //返回數(shù)組['uname', 'age']
// 3.獲得所有的屬性值
console.log(Object.values(o)) //返回數(shù)組['pink', 18]
// 4.對象的拷貝
const oo = {}
// 把o拷貝給oo
Object.assign(oo, o)
console.log(oo)
// 4.對象拷貝,給對象添加屬性
// 把屬性gender: '女'添加給o
Object.assign(o, {
gender: '女'
})
console.log(o)
</script>
</body>
</html>
(2)Array
-
Array
是內(nèi)置的構(gòu)造函數(shù),用于創(chuàng)建數(shù)組,建議使用字面量創(chuàng)建
,不用 Array構(gòu)造函數(shù)創(chuàng)建。 -
常見實例方法
-
reduce
:返回函數(shù)累計處理的結(jié)果,經(jīng)常用于求和等- 語法:
arr.reduce(function(累計值,當(dāng)前元素[,索引號][,源數(shù)組]){),起始值
- 說明:起始值可以省略,寫就作為第一次累計的起始值,不寫就是把數(shù)組的第一個值作為起始值,后面每次遍歷就會用后面的數(shù)組元素 累計到 累計值 里面
- 語法:
-
forEach
:用于遍歷數(shù)組,替代for
循環(huán) (重點) -
filter
:過濾數(shù)組單元值,生成新數(shù)組(重點) -
map
:迭代原數(shù)組,生成新數(shù)組(重點) -
join
:數(shù)組元素拼接為字符串,返回字符串(重點) -
find
:查找元素, 返回符合條件的第一個數(shù)組元素值,如果沒有返回 undefined(重點) -
every
:檢測數(shù)組所有元素是否都符合指定條件,如果所有元素都通過檢測返回 true,否則返回 false(重點) -
some
:檢測數(shù)組中的元素是否滿足指定條件 如果數(shù)組中有元素滿足條件返回 true,否則返回 false -
concat
: 合并兩個數(shù)組,返回生成新數(shù)組 -
sort
:對原數(shù)組單元值排序 -
splice
:刪除或替換原數(shù)組單元 -
reverse
:反轉(zhuǎn)數(shù)組 -
findIndex
:查找元素的索引值
-
案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array常用方法</title>
</head>
<body>
<script>
//reduce 返回函數(shù)累計處理的結(jié)果,經(jīng)常用于求和等
//arr.reduce(function(累計值, 當(dāng)前元素){}, 起始值)
const arr = [1, 2, 3]
//沒有給起始值的時候,數(shù)組第一個值就是起始值
arr.reduce(function(prev, item) {
console.log(prev) //1 3
return prev + item
})
//給起始值之后,用起始值
arr.reduce(function(prev, item) {
console.log(prev) //0 1 3
return prev + item
}, 0)
//find 查找元素, 返回符合條件的第一個數(shù)組元素值,如果沒有返回 undefined(重點)
const arr2 = ['red', 'blue', 'green']
const re1 = arr2.find(function(item) {
return item === 'blue'
})
console.log(re1) //blue
//every 每一個是否都符合條件,如果都符合返回 true ,否則返回false
const arr3 = [10, 20, 30]
const re2 = arr3.every(item => item >= 20)
console.log(re2) //false
</script>
</body>
</html>
-
常用靜態(tài)方法
- Array.from(arr):偽數(shù)組轉(zhuǎn)換為真數(shù)組
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>偽數(shù)組轉(zhuǎn)換為真數(shù)組</title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
// Array.from(lis) 把偽數(shù)組轉(zhuǎn)換為真數(shù)組
const lis = document.querySelectorAll('ul li')
console.log(lis)
// lis.pop() 報錯,偽數(shù)組不能直接操作
const liss = Array.from(lis)
liss.pop()
console.log(liss)
</script>
</body>
</html>
(3)String
-
String
是內(nèi)置的構(gòu)造函數(shù),用于創(chuàng)建字符串。String 也可以當(dāng)做普通函數(shù)使用,這時它的作用是強(qiáng)制轉(zhuǎn)換成字符串?dāng)?shù)據(jù)類型。 -
常用實例屬性
-
length
:用來獲取字符串的度長(重點)
-
-
常用實例方法
-
split('分隔符')
:用來將字符串拆分成數(shù)組(重點) -
substring(開始的索引號[,結(jié)束的索引號])
:用于字符串截取(重點) -
startsWith(檢測字符串[, 檢測位置索引號])
:檢測是否以某字符開頭(重點) -
includes(搜索的字符串[, 檢測位置索引號])
:判斷一個字符串是否包含在另一個字符串中,根據(jù)情況返回 true 或 false(重點) -
toUpperCase
:用于將字母轉(zhuǎn)換成大寫 -
toLowerCase
:用于將就轉(zhuǎn)換成小寫 -
indexOf
:檢測是否包含某字符 -
endsWith
:檢測是否以某字符結(jié)尾 -
replace
:用于替換字符串,支持正則匹配 -
match
:用于查找字符串,支持正則匹配
-
案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String常見方法</title>
</head>
<body>
<script>
// split 把字符串轉(zhuǎn)換為數(shù)組,和join()相反
const str = 'pink,red'
const arr = str.split(',')
console.log(arr) //['pink','red']
const str1 = '2022-4-8'
const arr1 = str1.split('-')
console.log(arr1) //['2022','4','8']
// substring(開始的索引號[, 結(jié)束的索引號]) 字符串的截取
// 如果省略結(jié)束的索引號,默認(rèn)取到最后
// 結(jié)束的索引號不包含想要截取的部分
const str2 = '今天又要做核酸了'
console.log(str2.substring(5, 7)) //核酸
// startsWith 判斷是不是以某個字符開頭
const str3 = 'pink老師上課中'
console.log(str3.startsWith('pink')) //true
// includes 判斷某個字符是不是包含在一個字符串里面
const str4 = '我是pink老師'
console.log(str4.includes('pink')) // true
// 轉(zhuǎn)換成字符串
const num = 10
console.log(String(num))
console.log(num.toString())
</script>
</body>
</html>
(4)Number
-
Number
是內(nèi)置的構(gòu)造函數(shù),用于創(chuàng)建數(shù)值,推薦使用字面量方式聲明數(shù)值,而不是Number
構(gòu)造函數(shù)。 -
常用實例方法
-
toFixed() :
設(shè)置保留小數(shù)位的長度
-
案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number常用方法</title>
</head>
<body>
<script>
// toFixed 方法可以讓數(shù)字指定保留的小數(shù)位數(shù)
const num = 10.923
console.log(num.toFixed()) //11
console.log(num.toFixed(1)) //10.9
const num1 = 10
console.log(num1.toFixed(2)) //10.00
</script>
</body>
</html>
3、綜合案例
- 需求:根據(jù)后臺提供的數(shù)據(jù),渲染購物車頁面
-
分析業(yè)務(wù)模塊:
-
渲染圖片、標(biāo)題、顏色、價格、贈品等數(shù)據(jù)
-
單價和小計模塊
-
總價模塊
-
-
解決方案:
-
把整體的結(jié)構(gòu)直接生成然后渲染到大盒子.list 里面
-
哪個方法可以遍歷的同時還有返回值?map 方法
-
最后計算總價模塊,那個方法可以求和?reduce 方法
-
-
實現(xiàn)細(xì)節(jié):
-
先利用map來遍歷,有多少條數(shù)據(jù),渲染多少相同商品,注意map返回值是數(shù)組,我們需要用 join 轉(zhuǎn)換為字符串,把返回的字符串 賦值 給 list 大盒子的 innerHTML。
-
更換數(shù)據(jù),先更換不需要處理的數(shù)據(jù),圖片,商品名稱,單價,數(shù)量,采取對象解構(gòu)的方式,注意 單價要保留2位小數(shù), 489.00 toFixed(2)
-
更換數(shù)據(jù),處理 規(guī)格文字 模塊,獲取 每個對象里面的 spec , 上面對象解構(gòu)添加 spec,獲得所有屬性值是: Object.values() 返回的是數(shù)組,拼接數(shù)組是 join(‘’) 這樣就可以轉(zhuǎn)換為字符串了
-
更換數(shù)據(jù),處理 贈品 模塊,獲取 每個對象里面的 gift,上面對象解構(gòu)添加 gift,注意要判斷是否有g(shù)if屬性,沒有的話不需要渲染,利用變成的字符串然后寫到 p.name里面
-
更換數(shù)據(jù),處理 小計 模塊,小計 = 單價 * 數(shù)量,小計名可以為: subTotal = price * count,注意保留2位小數(shù)。
-
計算 合計 模塊,求和用到數(shù)組 reduce 方法 累計器,根據(jù)數(shù)據(jù)里面的數(shù)量和單價累加和即可,注意 reduce方法有2個參數(shù),第一個是回調(diào)函數(shù),第二個是 初始值,這里寫 0。
-
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>綜合案例</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.list {
width: 990px;
margin: 100px auto 0;
}
.item {
padding: 15px;
transition: all .5s;
display: flex;
border-top: 1px solid #e4e4e4;
}
.item:nth-child(4n) {
margin-left: 0;
}
.item:hover {
cursor: pointer;
background-color: #f5f5f5;
}
.item img {
width: 80px;
height: 80px;
margin-right: 10px;
}
.item .name {
font-size: 18px;
margin-right: 10px;
color: #333;
flex: 2;
}
.item .name .tag {
display: block;
padding: 2px;
font-size: 12px;
color: #999;
}
.item .price,
.item .sub-total {
font-size: 18px;
color: firebrick;
flex: 1;
}
.item .price::before,
.item .sub-total::before,
.amount::before {
content: "¥";
font-size: 12px;
}
.item .spec {
flex: 2;
color: #888;
font-size: 14px;
}
.item .count {
flex: 1;
color: #aaa;
}
.total {
width: 990px;
margin: 0 auto;
display: flex;
justify-content: flex-end;
border-top: 1px solid #e4e4e4;
padding: 20px;
}
.total .amount {
font-size: 18px;
color: firebrick;
font-weight: bold;
margin-right: 50px;
}
</style>
</head>
<body>
<div class="list">
<!-- <div class="item">
<img src="https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg" alt="">
<p class="name">稱心如意手搖咖啡磨豆機(jī)咖啡豆研磨機(jī) <span class="tag">【贈品】10優(yōu)惠券</span></p>
<p class="spec">白色/10寸</p>
<p class="price">289.90</p>
<p class="count">x2</p>
<p class="sub-total">579.80</p>
</div> -->
</div>
<div class="total">
<div>合計:<span class="amount">1000.00</span></div>
</div>
<script>
const goodsList = [{
id: '4001172',
name: '稱心如意手搖咖啡磨豆機(jī)咖啡豆研磨機(jī)',
price: 289.9,
picture: 'https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg',
count: 2,
spec: {
color: '白色'
}
}, {
id: '4001009',
name: '竹制干泡茶盤正方形瀝水茶臺品茶盤',
price: 109.8,
picture: 'https://yanxuan-item.nosdn.127.net/2d942d6bc94f1e230763e1a5a3b379e1.png',
count: 3,
spec: {
size: '40cm*40cm',
color: '黑色'
}
}, {
id: '4001874',
name: '古法溫酒汝瓷酒具套裝白酒杯蓮花溫酒器',
price: 488,
picture: 'https://yanxuan-item.nosdn.127.net/44e51622800e4fceb6bee8e616da85fd.png',
count: 1,
spec: {
color: '青色',
sum: '一大四小'
}
}, {
id: '4001649',
name: '大師監(jiān)制龍泉青瓷茶葉罐',
price: 139,
picture: 'https://yanxuan-item.nosdn.127.net/4356c9fc150753775fe56b465314f1eb.png',
count: 1,
spec: {
size: '小號',
color: '紫色'
},
gift: '50g茶葉,清洗球,寶馬, 奔馳'
}]
// 1. 根據(jù)數(shù)據(jù)渲染頁面
document.querySelector('.list').innerHTML = goodsList.map(item => {
// console.log(item) // 每一條對象
// 對象解構(gòu) item.price item.count
const {
picture,
name,
count,
price,
spec,
gift
} = item
// 規(guī)格文字模塊處理
const text = Object.values(spec).join('/')
// 計算小計模塊 單價 * 數(shù)量 保留兩位小數(shù)
// 注意精度問題,因為保留兩位小數(shù),所以乘以 100 最后除以100
const subTotal = ((price * 100 * count) / 100).toFixed(2)
// 處理贈品模塊 '50g茶葉,清洗球'
const str = gift ? gift.split(',').map(item => `<span class="tag">【贈品】${item}</span> `).join('') : ''
return `
<div class="item">
<img src=${picture} alt="">
<p class="name">${name} ${str} </p>
<p class="spec">${text} </p>
<p class="price">${price.toFixed(2)}</p>
<p class="count">x${count}</p>
<p class="sub-total">${subTotal}</p>
</div>
`
}).join('')
// 3. 合計模塊
const total = goodsList.reduce((prev, item) => prev + (item.price * 100 * item.count) / 100, 0)
// console.log(total)
document.querySelector('.amount').innerHTML = total.toFixed(2)
</script>
</body>
</html>
實現(xiàn)效果:文章來源:http://www.zghlxwxcb.cn/news/detail-469202.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-469202.html
到了這里,關(guān)于JavaScript高級二、構(gòu)造函數(shù)&常用函數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!