reduce
當(dāng)你傳入一個初始值的時候,reduce函數(shù)會為你遍歷數(shù)組中的每一個元素;而當(dāng)你不傳初始值的時候,reduce則會拿第零個元素作為初始值,從第一個元素開始遍歷
sort
方法的默認比較函數(shù)會將所有比較對象都轉(zhuǎn)成字符串,即便里面的元素都是數(shù)字
在比較大小的時候,如果認為第一個參數(shù)應(yīng)當(dāng)排在第二個參數(shù)前面,則自定義比較函數(shù)需要返回一個負數(shù);如果第二個參數(shù)應(yīng)當(dāng)排在前面,則需要返回正數(shù);如果自定義比較函數(shù)返回0,則表示比較函數(shù)無法判斷孰大孰小。
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ù)對象
函數(shù)對象中包含一個Function.prototype的委托連接。函數(shù)對象通過該連接集成了兩個不是特別重要的方法,分別是apply和call。
當(dāng)前函數(shù)可執(zhí)行代碼的引用。
當(dāng)函數(shù)對象被創(chuàng)建的時候,這個函數(shù)對應(yīng)的活躍對象就被激活了,從而為閉包提供了可能性。函數(shù)可以通過這個隱藏屬性去訪問函數(shù)中創(chuàng)建它的變量。
函數(shù)是可嵌套的。當(dāng)嵌套的函數(shù)對象被創(chuàng)建時,它會包含一個外層函數(shù)對象所對應(yīng)的活躍對象引用。
generate
- 生成器用function*函數(shù)體創(chuàng)建函數(shù)對象,而該函數(shù)對象則會產(chǎn)生包含next方法的對象。
- 生成器介于純函數(shù)和非純函數(shù)之間。之前的constant生成器是純的,而大多數(shù)生成器則是非純的。
尾調(diào)用函數(shù)
當(dāng)一個函數(shù)返回另一個函數(shù)的返回值時,我們就稱其是一個尾調(diào)用。
function continuize(any) {
return function hero(fn2, ...args) {
return fn2(any(...args)); // 尾調(diào)用函數(shù)
}
}
promise && async / await
那就是將邏輯與控制流強耦合在了一起。這就必然導(dǎo)致低內(nèi)聚。