1.創建對象的6種方式:
?1. ob=new Object() ob.name='ah' ob.age=18
2. ob={name:'ah',gae:18}
3.工廠模式:
設計一個函數,專門生產Person類型的對象
<script>function createPerson(name,age,family) {var o = new Object();o.name = name;o.age = age;o.family = family;o.say = function(){alert(this.name);}return o;}p1=createPerson('ah',18,['l','ys'])
</script>
4.構造函數模式:
構造一個對象Person
<script>
function Person(name,age){this.name=namethis.age=agethis.sh=Function(){console.log('hi)}}p1=new Person('ah',18)
</script>
缺陷:構造函數也有其缺陷,每個實例都包含不同的Function實例( 構造函數內的方法在做同一件事,但是實例化后卻產生了不同的對象,方法是函數 ,函數也是對象)
5.原型模式創建對象
?
?????實例成員:實例化過程中的新加的屬性或方法(私有屬性或方法)
? ? 靜態成員:new 一個對象所具有的基本屬性或方法(一般屬性或方法)
? ? 公共成員:對象.prototype 的屬性或方法,可被重新賦值,可直接使用(公共屬性或方法)
prototype見:詳解prototype、__proto__和constructor_prototype和constructor-CSDN博客
<script>function Person() { }console.log(Person.prototype);//Object//創建公共屬性Person.prototype.name = 'ah'Person.prototype.age = 21;Person.prototype.family = ["lida", "lier", "wangwu"];Person.prototype.say = function () {alert(this.name);};console.log(Person.prototype);//{name: 'ah', age: 21, family: Array(3), say: ?}let p1 = new Personconsole.log(p1);//Person {}console.log(p1.name);//ah//單獨設置私有屬性/實例屬性:p1.sh = function () {console.log('hi', this.name);}console.log(p1);console.log(Person.prototype);p1.sh()//hi ahp2 = new Personp2.sh()//報錯</script>
6.原型模式+構造函數模式:
<script>function Person(name, age) {this.name = namethis.age = age}//設置一般的屬性,方法// 公共的的函數Person.prototype.sh = function () {console.log('hi', this.name);}console.log(Person);/*Person(name, age) {this.name = namethis.age = age}*/let p1 = new Person('ah', 18) //設置一般的屬性p1.sh() // hi ahconsole.log(p1);//Person {name: 'ah', age: 18}</script>
2.基本包裝類型:
詳情見:JS基礎知識(二十二):基本包裝類型_js包裝類型-CSDN博客
1.基本類型值: 指的是簡單的數據段Undefined、Null、Boolean、Number 和 String
2.引用類型值: 指那些可能由多個值構成的對象
3.基本包裝類型:為了便于操作基本類型值,ECMAScript 還提供了 3 個特殊的引用類型:Boolean、Number 和String。
與其他引用類型相似,但有各自類型相應的特殊方法,例如String的 ?s1.substring(2);
本來基本類型值不應有方法,但是有方法,這是因為后臺自動完成了一系列的處理,即
{
? ? ? ? ? ? ? ? 創建 String 類型的一個實例;
? ? ? ? ? ? ? ? 在實例上調用指定的方法;
? ? ? ? ? ? ? ? 銷毀這個實例;
?}經過以上處理,s1就跟個對象一樣了而且,上面這三個步驟也分別適用于 Boolean和 Number 類型對應的布爾值和數字值
引用類型 ?與 ?基本包裝類型 ?的主要區別就是對象的生存期
使用 new 操作符創建的引用類型的實例,在執行流離開當前作用域之前都一直保存在內存中。
而自動創建的基本包裝類型的對象,則只存在于一行代碼的執行瞬間,然后立即被銷毀。
3.Object的靜態方法:
? ? ? ? ?1.Object.keys(obj) ?返回一個數組,獲得屬性名
? ? ? ? ?2.Object.values(obj) 返回一個數組,獲得屬性值
? ? ? ? ?3.Object.assign(obj2, obj/{gender:'女'}) 將后者賦值/增加(拷貝)給前者 ?assign賦值,分配
<script>// 只有構造函數Object可以調用// 1.Object.keys(obj) 返回一個數組,獲得屬性名// 2.Object.values(obj) 返回一個數組,獲得屬性值// 3.Object.assign(obj2, obj) 將后者賦值(拷貝)給前者let obj = {name: 'ah',age: 18,sh: function () {alert(this.name)}}console.log(Object.keys(obj));console.log(Object.values(obj));let obj2 = {}Object.assign(obj2, obj)// 后者給前者console.log(obj2);// let arr = Object.keys(obj)// console.log(arr[0]);// console.log(arr[1]);</script>
4.Array的實例方法:
?1.forEach:遍歷,無返回值,本質上等同于 for 循環,對每一項執行 function 函數。
使用方法:
<!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><script>let arr = [1, 2, 3]let sum = 0arr.forEach(function (e) { sum += e })console.log(sum); //6</script>
</body></html>
2.map:迭代映射,map() 方法創建一個新數組,這個新數組由原數組中的每個元素都調用一次提供的函數后的返回值組成
使用方法:
<!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><script>const array1 = [1, 4, 9, 16];// Pass a function to mapconst map1 = array1.map((x) => x * 2);console.log(map1);// Expected output: Array [2, 8, 18, 32]</script>
</body></html>
?3.reduce:累計器
使用方法:
<script>const array1 = [1, 2, 3, 4];// 0 + 1 + 2 + 3 + 4const initialValue = 0; //initialValue初始值const sumWithInitial = array1.reduce((accumulator, currentValue) => accumulator + currentValue, //accumulator累加器 currentValue數組值initialValue,);console.log(sumWithInitial);// Expected output: 10</script>
相關過程:? ? ? ? ?
? 第一次調用回調時初始化 accumulator 的值。
? ? ? ? ? ? 如果指定了 initialValue,則 callbackFn 從數組中的第一個值作為 currentValue 開始執行,accumulator初始為initialValue
? ? ? ? ? ? 如果沒有指定 initialValue,則 accumulator 初始化為數組中的第一個值,并且 callbackFn 從數組中的第二個值作為 currentValue 開始執行。
? ? ? ? ? ? 在這種情況下,如果數組為空(沒有第一個值可以作為 accumulator 返回),則會拋出錯誤。
? ? ? ? ? ? 每次調用時,callbackFn 的返回值都作為 accumulator 參數傳遞到下一次調用中。
? ? ? ? ? ? accumulator 的最終值(也就是在數組的最后一次迭代中從 callbackFn 返回的值)將作為 reduce() 的返回值
4.filter:過濾返回數組
filter() 方法創建給定數組一部分的淺拷貝,其包含 通過所提供函數實現的測試 的所有元素。
使用方法:
<!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><script>// filter() 方法創建給定數組一部分的淺拷貝,其包含 通過所提供函數實現的測試 的所有元素。const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];const result = words.filter((word) => word.length > 6);console.log(result);// Expected output: Array ["exuberant", "destruction", "present"]</script>
</body></html>
5.join:整合
?join() 方法將一個數組(或一個類數組對象)的所有元素連接成一個字符串并返回這個字符串,用逗號或指定的分隔符字符串分隔。?如果數組只有一個元素,那么將返回該元素而不使用分隔符。
使用方法:
<!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><script>const elements = ['Fire', 'Air', 'Water'];console.log(elements.join());// Expected output: "Fire,Air,Water"console.log(elements.join(''));// Expected output: "FireAirWater"console.log(elements.join('-'));// Expected output: "Fire-Air-Water"</script>
</body></html>
6.find:查找第一個符合條件的,有則返回,無則undifind,可以用來根據對象的屬性篩選對象
使用方法:
<!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><script>const array1 = [5, 12, 8, 130, 44];const found = array1.find((element) => element > 10);//括號內寫查找的函數/要求console.log(found);// Expected output: 12</script>
</body></html>
7.every:測試所有元素
every() 方法測試一個數組內的所有元素是否都能通過指定函數的測試。它返回一個布爾值。
使用方法:
<!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><script>const isBelowThreshold = (currentValue) => currentValue < 40;const array1 = [1, 30, 39, 29, 10, 13];console.log(array1.every(isBelowThreshold));// Expected output: true</script>
</body></html>
8.some:測試是否包含
使用方法:
<!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><script>let arr = [1, 2, 3, 4]console.log(arr.some(x => x == 1)); //true</script>
</body></html>
9.findindex:找index,返回要找元素的下標,沒找到則返回-1
使用方法:
<!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><script>let arr = ['a', 'b', 'c', 'd']console.log(arr.findIndex(x => x == 'c'));</script>
</body></html>
特殊:Array.from():偽數組(可迭代對象)轉真數組
例如將獲得的 lis 數組轉化成真數組
案例:購物車展示
效果圖:
代碼:
<!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>* {margin: 0;padding: 0;list-style: none;box-sizing: border-box;}.banner {width: 1000px;height: 500px;margin: 0 auto;padding: 0 20px;border: 1px solid #000;}li {display: flex;width: 100%;height: 100px;margin-bottom: 6px;justify-content: space-between;}li img {width: 100px;}li div {width: 250px;text-align: center;color: red;}li span {color: #b3b3b3a5;font-size: 13px;}li .title {width: 100%;text-align: left;color: #000;}.total {text-align: right;}.total span {color: red;}</style>
</head><body><div class="banner"><ul><!-- 樣例布局,可留可刪 --><li><img src="https://img10.360buyimg.com/jdcms/s460x460_jfs/t1/163511/10/41642/167436/65e18381Fa56cd005/a3dd2c0fa6881ad0.jpg.webp"alt=""><div class="title">誠心如意手搖咖啡磨豆機<br><span>【贈品】</span><br><span>【贈品】</span></div><div><span>青色/一大</span></div><div>289.90</div><div><span>x2</span></div><div>279.80</div></li></ul><div class="total">合計:<span>798.00¥</span></div></div><script>const goodlists = [{name: 'Apple 蘋果 iPhone 15 Plus 二手手機 藍色 128G',price: 4999,picture: 'https://img20.360buyimg.com/jdcms/s460x460_jfs/t1/182034/34/38675/27903/650a62f5F522fd836/10fd8e1d1809b325.jpg.webp',count: 2,spec: { color: '藍色' },gifts: '充電線,耳機'},{name: '電腦臺式桌家用辦公桌子臥室小型簡約租房學生學習寫字桌簡易書桌 經典款-100CM白柳木 圓滑桌角 穩固承重',price: 116,picture: 'https://img12.360buyimg.com/jdcms/s460x460_jfs/t1/219000/19/39060/94643/65fdb31dF791b2494/d73fccc8ca386203.jpg.webp',count: 1,spec: { size: '150cm*100cm', color: '原木色' }},{name: '科技布藝沙發小戶型客廳臥室簡約單人雙人三人北歐簡易服裝店網紅 深藍色 科技布 80cm 單人位【廠家直銷】',price: 888,picture: 'https://img11.360buyimg.com/jdcms/s460x460_jfs/t1/112292/24/44663/84229/65d19513F0af948f9/105acfa9e3bdc391.jpg.webp',count: 1,spec: { size: '3m*1.5m', color: '紫色' }}]const ul = document.querySelector('.banner ul')const total = document.querySelector('.banner .total')let subtotal = [] //求和ul.innerHTML = goodlists.map(function (e) {subtotal.push(e.count * e.price)let str = ``if (Object.keys(e).find(x => x == 'gifts')) {// let arr = Object.values(e.gifts).join('').split(',')let arr = e.gifts.split(',')console.log(arr);for (x of arr) {str += `<br><span>【贈品】${x}</span>`}}return `<li><img src="${e.picture}"alt=""><div class="title">${e.name}${str}</div><div><span>${Object.values(e.spec).join('/')}</span></div><div>${e.price.toFixed(2)}</div><div><span>x${e.count}</span></div><div>${e.count * e.price}</div></li>`}).join('')let initialvalue = 0total.innerHTML = `合計:<span>${subtotal.reduce((a, initialvalue) => a + initialvalue)}¥</span>`</script>
</body></html>