1.箭頭函數(shù)
箭頭函數(shù)的傳參:
如果只傳遞一個(gè)參數(shù),小括號(hào)可以省略
如果沒(méi)有參數(shù)或者參數(shù)大于1個(gè),小括號(hào)不能省略
箭頭函數(shù)的返回值:
如果函數(shù)只有一行代碼,則大括號(hào)可以不寫(xiě)同時(shí)這一行代碼運(yùn)行結(jié)果將被直接返回,大括號(hào)不寫(xiě),則不要換行
const fun1 = (a) => a + 1;
console.log(fun1(5));
箭頭函數(shù)返回對(duì)象:
箭頭函數(shù)省略大括號(hào)情況下返回一個(gè)對(duì)象,需添加一個(gè)小括號(hào)
const fun1 = () => ({
username: '悟空',
age: 20,
password:'845353935'
});
console.log(fun1());
形參默認(rèn)值寫(xiě)法:
如果調(diào)用函數(shù)的時(shí)候沒(méi)有傳遞參數(shù),就使用默認(rèn)值參數(shù)
如果傳遞了參數(shù),就會(huì)使用傳遞的參數(shù)而不會(huì)使用默認(rèn)值
const func1 = (msg = '大家好') => {
console.log(msg);
};
func1("你好"); // '你好'
func1(); //'大家好'
2.解構(gòu)
數(shù)組解構(gòu):注重順序
const arr = [1, 2, 3, 4];
const [num1, num2] = arr;
console.log(num1, num2);//1 2
對(duì)象解構(gòu):注重屬性名
const obj = {
name: '老王',
age: 18,
skill: '翻墻'
};
const { name, skill } = obj;
console.log(name, skill);//'老王' '翻墻'
交換變量:
let a = 100;
let b = 200;
[a, b] = [b, a];
console.log(a, b);
3.對(duì)象的簡(jiǎn)寫(xiě)
對(duì)象屬性名和變量名一致時(shí)可以簡(jiǎn)寫(xiě)
對(duì)象方法可以省略冒號(hào)及function
const username = '悟空';
const skill = '72變';
const obj = {
username, //等價(jià)于username:username
skill, //等價(jià)于skill:skill
say(){
console.log('耍金箍棒'); // 等價(jià)于 say:function(){console.log('耍金箍棒')}
}
};
4.剩余運(yùn)算符
獲取剩余數(shù)據(jù):
剩余運(yùn)算符是一種比較方便我們獲取剩余數(shù)據(jù)的方式
const arr = [1, 2, 3, 4, 5];
const [letter1, letter2, ...list] = arr;
console.log(list);//[3,4,5]
const obj = { a: 1, b: 2, c: 3, d: 4 };
const { a, b, ...obj1 } = obj;
console.log(obj1);//{c:3,d:4}
獲取所有參數(shù):
利用剩余運(yùn)算符獲取到所有傳遞給calc的參數(shù) 封裝到params數(shù)組中
calc(1, 2, 3);
function calc(...params) {
console.log(params); //[1, 2, 3]
}
復(fù)制引用類型:
相當(dāng)于復(fù)制了一份引用類型的值 不再是同一個(gè)了 變成獨(dú)立的個(gè)體
const obj = { username: '悟空', age: 1080 };
const newObj = { ...obj };
newObj.username = '八戒';
console.log(obj);//{username: '悟空', age: 1080}
console.log(newObj);//{username: '八戒', age: 1080}
const arr = [1, 2, 3, 4];
const newArr = [...arr];
newArr.push(5);
console.log(arr);// [1, 2, 3, 4]
console.log(newArr);// [1, 2, 3, 4, 5]
5.數(shù)組方法
map
用于數(shù)據(jù)的改造
const arr = [1, 2, 3, 4];
const newArr = arr.map(item => item * 2);
console.log(newArr);//[2, 4, 6, 8]
filter
用于數(shù)據(jù)的查詢和刪除
可以遍歷指定數(shù)組,每次遍歷給回調(diào)函數(shù)傳入?yún)?shù),value 及 index
執(zhí)行回調(diào)函數(shù),如果回調(diào)函數(shù)的返回結(jié)果是true,就將元素存儲(chǔ)到filter內(nèi)部數(shù)組
最后將內(nèi)部數(shù)組返回
const arr = [1, 2, 3, 4, 5, 6];
const newArr = arr.filter(item => item > 3);
console.log(newArr); //[4,5,6]
forEach
單純數(shù)組遍歷
every
檢測(cè)數(shù)組元素的每個(gè)元素是否都符合條件 全符合則返回true 否則返回false
對(duì)于空數(shù)組 會(huì)直接返回true 不會(huì)去管判斷條件
const arr = ['葫蘆娃', '狗腿子', '蘿卜', '丸子'];
const res = arr.every(item => item.length > 2);
console.log(res); //flase
some
檢測(cè)數(shù)組元素 只要有一個(gè)元素滿足條件 就返回true
const arr = [
'健康',
'健康',
'健康',
'中招',
'健康',
'健康',
'健康',
'健康',
'健康',
'健康',
];
const result = arr.some((value) => value === '中招');//true