bind
2021/9/30
- 返回一个函数,通过
Function.prototype.apply()
将上下文绑定到fn上 - 使用扩展运算符
(...)
,将额外的参数传入
const myBind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);
不用箭头函数版:
const myBind = function(fn, context, ...boundArgs) {
return function (...args) {
return fn.apply(context, [...boundArgs, ...args]);
};
};
function foo (content, sign) {
return this.name + ' say ' + content + sign;
}
const obj = { name: '小禾' };
const fooBind = myBind(foo, obj);
console.log(fooBind('hi', '!')); // 小禾 say hi!
deepClone
2021/10/8
- 使用递归
- 用
if
判断传进来的参数是否为null
,是则return null
- 使用
Object.assign()
和{}
,创建一个浅拷贝对象 - 使用
Object.keys()
和Array.prototype.forEach()
判断哪些值需要深拷贝 - 判断传进来的参数是否为
Array
,是则定义拷贝对象的length属性(利用类数组对象知识点),并用Array.from(clone)
转为数组
function deepClone (obj) {
if (obj === null) return null;
let clone = Object.assign({}, obj); // 如果obj是数组,则['a','s'] => {'0':'a','1':'s'}
Object.keys(obj).forEach((key) => {
clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key];
});
if (Array.isArray(obj)) {
// 类数组对象转换数组
clone.length = obj.length;
return Array.from(clone);
}
return clone;
}
indexBy
2021/10/16
将一些特殊的值作为索引
- 使用
Array.prototype.reduce()
创建一个基于arr的Object; - 对arr的每个值,使用
fn
来创建一个key,并且将这个键值对放进object中; - indexBy函数可传入两个参数,arr和fn。
const indexBy = (arr, fn) =>
arr.reduce((obj, v, i) => {
obj[fn(v, i, arr)] = v;
return obj;
}, {});