babel
1、使用babel,需要安裝babel/core @babel/cli
2、在package.json文件中配置

3、安裝babel/preset-env

4、新建.babelrc文件配置

webpack
1、初始化項目
npm init
2、安裝webpack需要的包

3、配置webpack
新建webpack.config.js文件配置
4、配置,運行

npm run webpack
5、babel和webpack一起使用

6、html-webpack-plugin
安裝:

配置:

--------------------------------------------------------------promise------------------------------------------------
初識Promise
1、Promise 是異步操作的一種解決方案
Promise 一般用來解決層層嵌套的回調(diào)函數(shù)(回調(diào)地獄 callback hell)的問題
1.1、Promise的基本用法
實例化構(gòu)造函數(shù)生成實例對象
Promise 的狀態(tài) :Promise 有 3 種狀態(tài),一開始是 pending(未完成),執(zhí)行 resolve,變成 fulfilled(resolved),已成功
Promise 的狀態(tài)一旦變化,就不會再改變了
resolve 和 reject 函數(shù)的參數(shù)
const p = new Promise((resolve, reject) => {
reject(new Error('reason'));
});
p.then(
data => {
console.log('success', data);
},
err => {
console.log('error', err);
}
);
console.log(p);
2、 Promise的構(gòu)造函數(shù)方法
Promise.resolve是成功狀態(tài) Promise 的一種簡寫形式.
//下面兩種寫法相同
new Promise(resolve => resolve('foo'));
Promise.resolve('foo');
參數(shù)
一般參數(shù)
Promise.resolve('foo').then(data => {
console.log(data);
});
Promise對象:當 Promise.resolve() 接收的是 Promise 對象時,直接返回這個 Promise 對象,什么都不做
const p1 = new Promise(resolve => {
setTimeout(resolve, 1000, '我執(zhí)行了');
// setTimeout(() => {
// resolve('我執(zhí)行了');
// }, 1000);
});
Promise.resolve(p1).then(data => {
console.log(data);
});
// 等價于
p1.then(data => {
console.log(data);
});
console.log(Promise.resolve(p1) === p1);
當 resolve 函數(shù)接收的是 Promise 對象時,后面的 then 會根據(jù)傳遞的 Promise 對象的狀態(tài)變化決定執(zhí)行哪一個回調(diào)
new Promise(resolve => resolve(p1)).then(data => {
console.log(data);
});
具有then方法的對象
const thenable = {
then(resolve, reject) {
console.log('then');
resolve('data');
// reject('reason');
}
};
Promise.resolve(thenable).then(
data => console.log(data),
err => console.log(err)
);
console.log(Promise.resolve(thenable));
Promise.reject() 失敗狀態(tài) Promise 的一種簡寫形式
new Promise((resolve, reject) => {
reject('reason');
});
等價于
Promise.reject('reason');
不管什么參數(shù),都會原封不動地向后傳遞,作為后續(xù)方法的參數(shù)
const p1 = new Promise(resolve => {
setTimeout(resolve, 1000, '我執(zhí)行了');
});
Promise.reject(p1).catch(err => console.log(err));
new Promise((resolve, rejcet) => {
resolve(123);
})
.then(data => {
// return data;
// return Promise.resolve(data);
return Promise.reject('reason');
})
.then(data => {
console.log(data);
})
.catch(err => console.log(err));
Promise.all()關注多個 Promise 對象的狀態(tài)變化,傳入多個 Promise 實例,包裝成一個新的 Promise 實例返回
Promise.all() 的狀態(tài)變化與所有傳入的 Promise 實例對象狀態(tài)有關
所有狀態(tài)都變成 resolved,最終的狀態(tài)才會變成 resolved
只要有一個變成 rejected,最終的狀態(tài)就變成 rejected
const delay = ms => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
const p1 = delay(1000).then(() => {
console.log('p1 完成了');
// return 'p1';
return Promise.reject('reason');
});
const p2 = delay(2000).then(() => {
console.log('p2 完成了');
return 'p2';
// return Promise.reject('reason');
});
const p = Promise.all([p1, p2]);
p.then(
data => {
console.log(data);
},
err => {
console.log(err);
}
);
Promise.race() Promise.race() 的狀態(tài)取決于第一個完成的 Promise 實例對象,如果第一個完成的成功了,那最終的就成功;如果第一個完成的失敗了,那最終的就失敗
const delay = ms => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
const p1 = delay(1000).then(() => {
console.log('p1 完成了');
return 'p1';
});
const p2 = delay(2000).then(() => {
console.log('p2 完成了');
return Promise.reject('reason');
});
const racePromise = Promise.race([p1, p2]);
racePromise.then(
data => {
console.log(data);
},
err => {
console.log(err);
}
);
Promise.allSettled() 的狀態(tài)與傳入的Promise 狀態(tài)無關,永遠都是成功的,它只會忠實的記錄下各個 Promise 的表現(xiàn)。
const delay = ms => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
const p1 = delay(1000).then(() => {
console.log('p1 完成了');
return 'p1';
});
const p2 = delay(2000).then(() => {
console.log('p2 完成了');
return Promise.reject('reason');
});
const allSettledPromise = Promise.allSettled([p1, p2]);
allSettledPromise.then(data => {
console.log('succ', data);
});
3、Promise的實例方法
then方法
pending->fulfilled 時,執(zhí)行 then 的第一個回調(diào)函數(shù)
pending->rejected 時,執(zhí)行 then 的第二個回調(diào)函數(shù)
then 方法執(zhí)行后默認是返回一個新的成功狀態(tài)的Promise對象
const p = new Promise((resolve, reject) => {
reject();
});
p.then(
() => {
// console.log('success');
},
() => {
console.log('err');
// 在 then 的回調(diào)函數(shù)中,return 后面的東西,會用 Promise 包裝一下
return 123;
// 等價于
// return new Promise(resolve => {
// resolve(123);
// });
}
)
.then(
data => {
console.log('success2', data);
return new Promise(resolve => {
resolve(undefined);
});
},
err => {
console.log('err2', err);
}
)
.then(
data => {
console.log('success3', data);
},
err => {
console.log('err3', err);
}
);
catch方法,專門用來處理 rejected 狀態(tài),本質(zhì)上是 then 的特例
catch() 可以捕獲它前面的錯誤
一般總是建議,Promise 對象后面要跟 catch 方法,這樣可以處理 Promise 內(nèi)部發(fā)生的錯誤
new Promise((resolve, reject) => {
reject('reason');
})
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
throw new Error('reason');
})
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
finally,本質(zhì)上是 then() 的特例。
當 Promise 狀態(tài)發(fā)生變化時,不論如何變化都會執(zhí)行,不變化不執(zhí)行
new Promise((resolve, reject) => {
// resolve(123);
reject('reason');
})
.finally(data => {
console.log(data);
})
.catch(err => {});
4、Promise的注意事項和應用
resolve 或 reject 函數(shù)執(zhí)行后的代碼
推薦在調(diào)用 resolve 或 reject 函數(shù)的時候加上 return,不再執(zhí)行它們后面的代碼
Promise.all/race/allSettled 的參數(shù)問題
參數(shù)如果不是 Promise 數(shù)組,會將不是 Promise 的數(shù)組元素轉(zhuǎn)變成 Promise 對象
Promise.all/race/allSettled 的錯誤處理
錯誤既可以單獨處理,也可以統(tǒng)一處理,一旦被處理,就不會在其他地方再處理一遍
異步加載圖片
// 異步加載圖片
const loadImgAsync = url => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve(img);
};
img.onerror = () => {
reject(new Error(`Could not load image at ${url}`));
};
img.src = url;
});
};
const imgDOM = document.getElementById('img');
loadImgAsync('https://2img.mukewang.com/5f057a6a0001f4f918720764.jpg')
.then(img => {
console.log(img.src);
setTimeout(() => {
imgDOM.src = img.src;
}, 1000);
})
.catch(err => {
console.log(err);
});
----------------------------------------es6新增方法------------------------------------------------------
1、字符串的新增方法
includes 判斷字符串中是否含有某些字符
(1)基本用法
console.log('abc'.includes('a')); // true
console.log('abc'.includes('ab')); //true
console.log('abc'.includes('bc')); //true
console.log('abc'.includes('ac')); // false
(2)參數(shù)
/*
第一個參數(shù),必需,要查找的字符串。
第二個參數(shù),可選,設置從那個位置開始查找,默認為 0
*/
console.log('abc'.includes('a')); //true
console.log('abc'.includes('a', 0)); //true
console.log('abc'.includes('a', 1)); // false
(3)應用 拼接url地址
let url = 'https://www.imooc.com/course/list?';
const addURLParam = (url, name, value) => {
url += url.includes('?') ? '&' : '?';
url += `${name}=${value}`;
return url;
};
url = addURLParam(url, 'c', 'fe');
console.log(url);
url = addURLParam(url, 'sort', 'pop');
console.log(url);
padStart和padEnd 補全字符串
(1)基本用法
console.log('x'.padStart(5, 'ab')); //ababx
console.log('x'.padEnd(5, 'ab')); //xabab
console.log('x'.padEnd(4, 'ab')); // xaba
(2)注意事項
原字符串的長度,等于或大于最大長度,不會消減原字符串,字符串補全不生效,返回原字符串
console.log('xxx'.padStart(2, 'ab')); // xxx
console.log('xxx'.padEnd(2, 'ab')); // xxx
用來補全的字符串與原字符串長度之和超過了最大長度,截去超出位數(shù)的補全字符串,原字符串不動
console.log('abc'.padStart(10, '0123456789')); //0123456abc
console.log('abc'.padEnd(10, '0123456789')); // abc0123456
如果省略第二個參數(shù),默認使用空格補全長度
console.log('x'.padStart(4)); // x
console.log('x'.padEnd(4)); // x
(3)應用
padStart 顯示日期
// 2020-10-10
console.log('10'.padStart(2, 0)); // 10
console.log('1'.padStart(2, 0)); // 01
trimStart和trimEnd方法,清除字符串的首或尾空格,中間的空格不會清除
(1)基本用法
const s = ' a b c ';
console.log(s.trimStart());
console.log(s.trimLeft());
console.log(s.trimEnd());
console.log(s.trimRight());
(2)應用: 提交數(shù)據(jù)時,去掉首尾空格
<input type="text" id="username" />
<input type="submit" value="提交" id="btn" />
<script>
const usernameInput = document.getElementById('username');
const btn = document.getElementById('btn');
btn.addEventListener(
'click',
() => {
console.log(usernameInput.value);
// 驗證
console.log(usernameInput.value.trim());
if (usernameInput.value.trim() !== '') {
// 可以提交
console.log('可以提交');
} else {
// 不能提交
console.log('不能提交');
}
// 手動提交
},
false
);
</script>
2、數(shù)組的新增方法
includes 判斷數(shù)組中是否含有某個成員
(1)基本用法
console.log([1, 2, 3].includes('2')); // false
console.log([1, 2, 3].includes(2)); // true
(2)參數(shù)
/*
第一個參數(shù),必須,需要查找的元素值。
第二個參數(shù),可選,從該索引處開始查找 searchElement。如果為負值,則按升序從 array.length + fromIndex 的索引開始搜索。默認為 0。
*/
console.log([1, 2, 3].includes(2, 2)); // false
console.log([1, 2, 3].includes(2, -2)); //true
console.log([1, 2, 3].includes(3)); // false
(3)注意事項:基本遵循嚴格相等(===),但是對于 NaN 的判斷與 === 不同,includes 認為 NaN === NaN
console.log(NaN === NaN); // false
console.log([1, 2, NaN].includes(NaN)); // true
(4)應用 數(shù)組去重
const arr = [];
for (const item of [1, 2, 1]) {
if (!arr.includes(item)) {
arr.push(item);
}
}
console.log(arr);
Array.from 將其他數(shù)據(jù)類型轉(zhuǎn)換成數(shù)組
(1)基本用法
console.log(Array.from('str')); // ["s", "t", "r"]
(2)可以通過 Array.from() 轉(zhuǎn)換成數(shù)組
所有可遍歷的 數(shù)組、字符串、Set、Map、NodeList、arguments
console.log(Array.from(new Set([1, 2, 1]))); // [1, 2]
// 等價于
console.log([...new Set([1, 2, 1])]);
擁有 length 屬性的任意對象
const obj = {
'0': 'a',
'1': 'b',
name: 'Alex',
length: 3
};
console.log(Array.from(obj));
(3)參數(shù)
// 3.第二個參數(shù) : 數(shù)組中每個元素要調(diào)用的函數(shù)
// 作用類似于數(shù)組的 map 方法,用來對每個元素進行處理,將處理后的值放入返回的數(shù)組
console.log(
[1, 2].map(value => {
return value * 2;
})
);
console.log(Array.from('12', value => value * 2));
console.log(Array.from('12').map(value => value * 2));
// 4.第三個參數(shù) 映射函數(shù)(mapFunction)中的 this 對象
Array.from(
'12',
value => {
console.log(this);
},
document
);
Array.from(
'12',
function () {
console.log(this);
},
document
);
find和 findIndex方法
find():找到滿足條件的一個立即返回值
findIndex():找到滿足條件的一個,立即返回其索引
(1)參數(shù)
參數(shù) 描述
function(currentValue, index,arr) 必須。數(shù)組每個元素需要執(zhí)行的函數(shù)。1、currentValue 必需,當前元素。2、index,可選,當前元素的索引。3、arr,可選。當前元素所屬的數(shù)組對象
thisValue 可選。 傳遞給函數(shù)的值一般用 "this" 值。如果這個參數(shù)為空, "undefined" 會傳遞給 "this" 值
(2)代碼示例
console.log(
[1, 5, 10, 15].find((value, index, arr) => {
// console.log(value, index, arr);
console.log(this);
return value > 9;
}, document)
);
[1, 5, 10, 15].find(function(value, index, arr) {
// console.log(value, index, arr);
console.log(this);
return value > 9;
}, document);
console.log(
[1, 5, 10, 15].findIndex((value, index, arr) => {
// console.log(value, index, arr);
return value > 9;
}, document)
);
(3)應用 從獲取到數(shù)據(jù)中篩選數(shù)據(jù)
const students = [
{
name: '張三',
sex: '男',
age: 16
},
{
name: '李四',
sex: '女',
age: 22
},
{
name: '王二麻子',
sex: '男',
age: 32
}
];
console.log(students.find(value => value.sex === '女'));
console.log(students.findIndex(value => value.sex === '女'));
3、對象的新增方法
Object.assign 合并對象,相當于將后面的對象合并到第一個對象中
(1)基本使用
// Object.assign(目標對象, 源對象1,源對象2,...): 目標對象
const apple = {
color: '紅色',
shape: '圓形',
taste: '甜'
};
const pen = {
color: '黑色',
shape: '圓柱形',
use: '寫字'
};
console.log(Object.assign(apple, pen));
// console.log(Object.assign(apple, pen) === apple); true
(2)注意事項
基本數(shù)據(jù)類型作為源對象 與對象的展開類似,先轉(zhuǎn)換成對象,再合并
console.log(Object.assign({}, undefined));
console.log(Object.assign({}, null));
console.log(Object.assign({}, 1));
console.log(Object.assign({}, true));
console.log(Object.assign({}, 'str'));
同名屬性的替換 , 后面的直接覆蓋前面的
const apple = {
color: ['紅色', '黃色'],
shape: '圓形',
taste: '甜'
};
const pen = {
color: ['黑色', '銀色'],
shape: '圓柱形',
use: '寫字'
};
console.log(Object.assign({}, apple, pen));
(3)應用 合并默認參數(shù)和用戶參數(shù)
const logUser = userOptions => {
const DEFAULTS = {
username: 'ZhangSan',
age: 0,
sex: 'male'
};
const options = Object.assign({}, DEFAULTS, userOptions);
// const options = Object.assign({}, DEFAULTS, undefined);
console.log(options);
};
logUser();
// logUser({});
// logUser({ username: 'Alex' });
Object.keys 獲取對象中屬性名的集合
Object.value 獲取對象中屬性值值的集合
Object.entries 獲取對象中屬性和值的集合
(1)基本用戶
const person = {
name: 'Alex',
age: 18
};
console.log(Object.keys(person));
console.log(Object.values(person));
console.log(Object.entries(person));
(2)與數(shù)組類似方法的區(qū)別
數(shù)組的 keys()、values()、entries() 等方法是實例方法,返回的都是 Iterator
對象的 Object.keys()、Object.values()、Object.entries() 等方法是構(gòu)造函數(shù)方法,返回的是數(shù)組
const person = {
name: 'Alex',
age: 18
};
console.log([1, 2].keys());
console.log([1, 2].values());
console.log([1, 2].entries());
console.log(person.keys);
(2)使用 for...of 循環(huán)遍歷對象
for (const key of Object.keys(person)) {
console.log(key);
}
for (const value of Object.values(person)) {
console.log(value);
}
for (const entries of Object.entries(person)) {
console.log(entries);
}
--------------------------------------------------------遍歷器和for循環(huán)---------------------------------------
1、Iterator是什么
Iterator 是 ES6 引入的一種新的遍歷機制,Iterator本質(zhì)是一個指針對象,其中包含一個next方法,這個方法可以改變指針的指向,并且返回一個包含value和done的對象,value為當前所指向的成員的值,done表示是否遍歷完成
可遍歷數(shù)據(jù)原型繼承了Symbol.iterator
const it = [1, 2]Symbol.iterator;
console.log(it);
可以調(diào)用Iterator的next方法,查看遍歷的過程
const it = [1, 2]Symbol.iterator;
/*
value:當前屬性的值
done:判斷是否遍歷結(jié)束 為 true 時則遍歷結(jié)束
*/
console.log(it.next()); // {value: 1, done: false}
console.log(it.next()); // {value: 2, done: false}
console.log(it.next()); // {value: undefined, done: true}
console.log(it.next()); // {value: undefined, done: true}
2、Iterator解惑
為什么需要 Iterator 遍歷器 :為了統(tǒng)一遍歷的方式,在ES6推出了Iterator遍歷機制
遍歷數(shù)組:for 循環(huán)和 forEach 方法
遍歷對象:for in 循環(huán)
如何更方便的使用 Iterator: 使用for...of方法遍歷
3、for...of用法
for...of循環(huán)的本質(zhì)就是將next方法遍歷的過程封裝,只遍歷那些 done 為 false 時,對應的 value 值
// 使用next遍歷過程
const arr = [1, 2, 3];
const it = arr[Symbol.iterator]();
let next = it.next();
while (!next.done) {
console.log(next.value);
next = it.next();
}
// 使用for...of直接就遍歷了
for (const item of arr) {
console.log(item);
}
4、for...of的使用
與break和continue關鍵字結(jié)合使用
const arr = [1, 2, 3];
for (const item of arr) {
if (item === 2) {
// break;
continue;
}
console.log(item);
}
在 for...of 中取得數(shù)組的索引
keys() 得到的是索引的可遍歷對象,可以遍歷出索引值
const arr = [1, 2, 3];
for (const key of arr.keys()) {
console.log(key);
}
```
values() 得到的是值的可遍歷對象,可以遍歷出值
```
const arr = [1, 2, 3];
for (const value of arr.values()) {
console.log(value);
}
```
entries() 得到的是索引+值組成的數(shù)組的可遍歷對象
const arr = [1, 2, 3];
for (const entries of arr.entries()) {
console.log(entries);
}
```
5、原生可遍歷和非原生可遍歷對象
只要有 Symbol.iterator 方法,并且這個方法可以生成可遍歷對象,就是可遍歷的,可以使用 for...of 循環(huán)來統(tǒng)一遍歷
原生可遍歷對象
數(shù)組
字符串
Set
Map
arguments
NodeList
非原生可遍歷對象
一般對象 var obj ={}
手動添加Iterator,然后使用for...of遍歷
const person = { sex: 'male', age: 18 };
person[Symbol.iterator] = () => {
let index = 0;
return {
next() {
index++;
if (index === 1) {
return {
value: person.age,
done: false
};
} else if (index === 2) {
return {
value: person.sex,
done: false
};
} else {
return {
done: true
};
}
}
};
};
for (const item of person) {
console.log(item);
}
有l(wèi)ength和數(shù)字索引的對象
// 有 length 和索引屬性的對象
const obj = {
'0': 'alex',
'1': 'male',
length: 2
};
// 第一種方法,直接設置iterator
obj[Symbol.iterator] = Array.prototype[Symbol.iterator];
// 第二種方法,手動添加iterator
obj[Symbol.iterator] = () => {
let index = 0;
return {
next() {
let value, done;
if (index < obj.length) {
value = obj[index];
done = false;
} else {
value = undefined;
done = true;
}
index++;
return {
value,
done
};
}
};
};
for (const item of obj) {
console.log(item);
}
6、使用了Iterator的場合
所有的原生可遍歷對象
數(shù)組的展開運算符
數(shù)組的解構(gòu)賦值
Set 和 Map 的構(gòu)造函數(shù)
-------------------------------------------set和map---------------------------------------------
1、什么是Set
set是一系列無序,沒有重復值的集合
Set中不能有重復的成員
const s = new Set();
s.add(1);
s.add(2);
s.add(1);
console.log(s); //{1, 2}
Set 沒有下標去標示每一個值,所以 Set 是無序的,也不能像數(shù)組那樣通過下標去訪問 Set 的成員
2、Set實例的方法和屬性
方法
add 添加成員
delete 刪除成員
clear 清除成員
has 判斷是否包含某一個成員
forEach 遍歷獲取所有的成員
const s = new Set();
s.add(1).add(2).add(2);
s.forEach(function (value, key, set) {
// Set 中 value = key
console.log(value, key, set === s);
// console.log(this);
}, document);
console.log(s);
屬性
size 獲取所有的成員個數(shù)
3、Set構(gòu)造函數(shù)的參數(shù)
數(shù)組、字符串、arguments、NodeList、Set 等都可以作為參數(shù)傳遞
<p>1</p>
<p>2</p>
<p>3</p>
<script>
// 1.數(shù)組
const s = new Set([1, 2, 1]);
console.log(s); // {1, 2}
// 2.字符串、arguments、NodeList、Set 等
console.log(new Set('hi')); //{"h", "i"}
function func() {
console.log(new Set(arguments));//{1, 2}
}
func(1, 2, 1);
console.log(new Set(document.querySelectorAll('p'))); //{p, p, p}
const s1 = new Set([1, 2, 1]);
console.log(new Set(s1) === s1); // false
console.log(s1); //{1, 2}
</script>
4、Set注意事項
判斷重復的方式
Set 對重復值的判斷基本遵循嚴格相等(===)
但是對于 NaN 的判斷與 === 不同,Set 中 NaN 等于 NaN
const s1 = new Set([1, 2, 1]); // {1,2}
const s2 = new Set([NaN, 2, NaN]); // {NaN, 2}
什么時候使用 Set
數(shù)組或字符串去重時
不需要通過下標訪問,只需要遍歷時
為了使用 Set 提供的方法和屬性時(add delete clear has forEach size 等)
5、Set的應用
數(shù)組去重
const s = new Set([1, 2, 1]);
console.log(s); // {1,2}
字符串去重
const s = new Set('abbacbd');
console.log([...s].join(''));
console.log(s);
存放DOM元素,使用forEach方法遍歷
const s = new Set(document.querySelectorAll('p'));
console.log(s);
s.forEach(function (elem) {
// console.log(elem);
elem.style.color = 'red';
elem.style.backgroundColor = 'yellow';
});
6、認識 Map
Map 和對象都是鍵值對的集合
Map 和對象的區(qū)別
對象:一般使用字符串作為鍵名
Map:所有的數(shù)據(jù)類型都可以作為鍵名
const m = new Map();
m.set('name', 'alex');
m.set(true, 'true');
m.set({}, 'object');
m.set(new Set([1, 2]), 'set');
m.set(undefined, 'undefined');
console.log(m);
7、Map實例的方法和屬性
方法
set 添加成員
get 獲取成員
clear 清除成員
has 判斷是否包含某一個成員
forEach 遍歷獲取所有的成員
delete 刪除某一個成員
clear 清除所有的成員
屬性
size 獲取所有的成員個數(shù)
8、Map 構(gòu)造函數(shù)的參數(shù)
只能傳二維數(shù)組,而且必須體現(xiàn)出鍵和值
new Map(['name', 'alex', 'age', 18])
Set、Map 實例等,也必須體現(xiàn)出鍵和值
// Set 中也必須體現(xiàn)出鍵和值
const s = new Set([
['name', 'alex'],
['age', 18]
]);
console.log(new Map(s));
console.log(s);
// Map
// 復制了一個新的 Map
const m1 = new Map([
['name', 'alex'],
['age', 18]
]);
console.log(m1);
const m2 = new Map(m1);
console.log(m2, m2 === m1);
9、Map的注意事項
判斷重復的方式
Map 對重復值的判斷基本遵循嚴格相等(===)但是對于 NaN 的判斷與 === 不同,Set 中 NaN 等于 NaN
const s1 = new Set([1, 2, 1]); // {1,2}
const s2 = new Set([NaN, 2, NaN]); // {NaN, 2}
什么時候使用 Map
如果只是需要 key -> value 的結(jié)構(gòu),或者需要字符串以外的值做鍵,使用 Map 更合適
10、Map的應用
使用Map操作DOM對象,設置樣式
<p>1</p>
<p>2</p>
<p>3</p>
<script>
const [p1, p2, p3] = document.querySelectorAll('p');
// console.log(p1, p2, p3);
// const m = new Map();
// m.set(p1, 'red');
// m.set(p2, 'green');
// m.set(p3, 'blue');
const m = new Map([
[
p1,
{
color: 'red',
backgroundColor: 'yellow',
fontSize: '40px'
}
],
[
p2,
{
color: 'green',
backgroundColor: 'pink',
fontSize: '40px'
}
],
[
p3,
{
color: 'blue',
backgroundColor: 'orange',
fontSize: '40px'
}
]
]);
m.forEach((propObj, elem) => {
for (const p in propObj) {
elem.style[p] = propObj[p];
}
});
// m.forEach((color, elem) => {
// elem.style.color = color;
// });
console.log(m);
</script>