reduce
當(dāng)你傳入一個(gè)初始值的時(shí)候,reduce函數(shù)會(huì)為你遍歷數(shù)組中的每一個(gè)元素;而當(dāng)你不傳初始值的時(shí)候,reduce則會(huì)拿第零個(gè)元素作為初始值,從第一個(gè)元素開(kāi)始遍歷
sort
方法的默認(rèn)比較函數(shù)會(huì)將所有比較對(duì)象都轉(zhuǎn)成字符串,即便里面的元素都是數(shù)字
在比較大小的時(shí)候,如果認(rèn)為第一個(gè)參數(shù)應(yīng)當(dāng)排在第二個(gè)參數(shù)前面,則自定義比較函數(shù)需要返回一個(gè)負(fù)數(shù);如果第二個(gè)參數(shù)應(yīng)當(dāng)排在前面,則需要返回正數(shù);如果自定義比較函數(shù)返回0,則表示比較函數(shù)無(wú)法判斷孰大孰小。
function refine(collection, path) {
return path.reduce(function (refinement, element) {
try {
return refinement[element];
} catch (error) {}
}, collection);
}
const by = (...keys) => {
const paths = keys.map((item) => item.toString().split("."));
return (first, second) => {
let first_value, second_value;
if (
paths.every(function (path) {
first_value = refine(first, path);
second_value = refine(second, path);
return first_value === second_value;
})
) {
return 0;
}
return (
typeof first_value === typeof second_value
? first_value < second_value
: typeof first_value < typeof second_value
)
? -1
: 1;
};
};
let people = [
{ first: "Frank", last: "Farkel" },
{ first: "Fanny", last: "Farkel" },
{ first: "Sparkle", last: "Farkel" },
{ first: "Charcoal", last: "Farkel" },
{ first: "Mark", last: "Farkel" },
{ first: "Simon", last: "Farkel" },
{ first: "Gar", last: "Farkel" },
{ first: "Ferd", last: "Berfel" },
];
people.sort(by("first", "second"));
console.log(people);
WeakMap
function factory() {
const map = new WeakMap()
return {
seal: (object) => {
const box = Object.freeze(Object.create(null))
map.set(box, object)
return map
},
unseal: (box) => {
return map.get(box)
}
}
}
Object.freeze && const
Object.freeze是作用于值的,而const則作用于變量
函數(shù)對(duì)象
函數(shù)對(duì)象中包含一個(gè)Function.prototype的委托連接。函數(shù)對(duì)象通過(guò)該連接集成了兩個(gè)不是特別重要的方法,分別是apply和call。
當(dāng)前函數(shù)可執(zhí)行代碼的引用。
當(dāng)函數(shù)對(duì)象被創(chuàng)建的時(shí)候,這個(gè)函數(shù)對(duì)應(yīng)的活躍對(duì)象就被激活了,從而為閉包提供了可能性。函數(shù)可以通過(guò)這個(gè)隱藏屬性去訪問(wèn)函數(shù)中創(chuàng)建它的變量。
函數(shù)是可嵌套的。當(dāng)嵌套的函數(shù)對(duì)象被創(chuàng)建時(shí),它會(huì)包含一個(gè)外層函數(shù)對(duì)象所對(duì)應(yīng)的活躍對(duì)象引用。
generate
- 生成器用function*函數(shù)體創(chuàng)建函數(shù)對(duì)象,而該函數(shù)對(duì)象則會(huì)產(chǎn)生包含next方法的對(duì)象。
- 生成器介于純函數(shù)和非純函數(shù)之間。之前的constant生成器是純的,而大多數(shù)生成器則是非純的。
尾調(diào)用函數(shù)
當(dāng)一個(gè)函數(shù)返回另一個(gè)函數(shù)的返回值時(shí),我們就稱其是一個(gè)尾調(diào)用。
function continuize(any) {
return function hero(fn2, ...args) {
return fn2(any(...args)); // 尾調(diào)用函數(shù)
}
}
promise && async / await
那就是將邏輯與控制流強(qiáng)耦合在了一起。這就必然導(dǎo)致低內(nèi)聚。