# 实现 lodash 的_.get
# 上期回顾
# 一堆整数,分三份,尽量和相等
function a1(arr, count) {
arr.sort((a, b) => b - a);
const arg = arr.reduce((a, total) => a + total) / count;
const resArr = [];
let current = 0;
for (let i = 0; i < count - 1; i++) {
if (current + arr[arr.length - 1] / 2 < arg && i) {
arr.pop();
resArr[i - 1].push(arr[arr.length - 1]);
}
current = 0;
resArr[i] = [];
arr.forEach((item, index) => {
current += item;
arr.splice(index, 1);
resArr[i].push(item);
if (current > arg) {
arr.splice(index, 0, item);
resArr[i].pop();
current -= item;
}
});
}
resArr[count - 1] = arr;
return resArr;
}
# 今日解题
# _.get
函数是为了解决像a.b.c.d.e
这样嵌套复杂的情况,提高容错性
function get(object, path, defaulltValue = undefined) {
/// a[3].b -> a.3.b -> [a,3,b]
// path中也可能是数组的路径,全部转化成 . 运算符并组成数组
const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
let result = object;
for (const p of paths) {
// null 与 undefined 取属性会报错,所以使用Object包装一下
result = Object(result)[p];
if (result == undefined) {
return defaultValue;
}
}
return result;
}
console.log(get({ a: null }, "a.b.c", 3)); /// 3
console.log(get({ a: undefined }, "a", 3)); /// 3
console.log(get({ a: null }, "a", 3)); /// 3
console.log(get({ a: [{ b: 1 }] }, "a[0].b", 3)); /// 1
如果不考虑数组的情况
function get(object, paths, defaultValue = undefined) {
return (
paths.split(".").reduce((total, now) => (total || {})[now], object) ||
defaultValue
);
}