问题
实现lodash_.get,即链式调用
https://www.lodashjs.com/docs/lodash.get
答案
const obj = {a: [{b: {cd: 0}}]}const v1 = this.test(obj, "a.b.cd", 100);const v2 = this.test(obj, "a[0].b.cd");const v3 = this.test(obj, ['a', '0', 'b', 'c']);const v4 = this.test(obj, ['a', '0', 'b', 'cd']);const v5 = this.test(obj, 'abc');const v6 = this.test(obj, 'a');console.log("path", v1, v2, v3, v4, v5, v6);
test(obj, path, defaultValue) {let item = obj;let value = defaultValue || 'default';// 合成最终数组let arr = [];if (/\./g.test(path)) {path = path.replace(/(\.)(\w+)/g, '[$2]');path = path.replace(/^(\w+)(\[)/g,'[$1]$2');arr = path.match(/(\w+)/g)} else {if (Array.isArray(path)) {arr = path;} else {arr = [path];}}for(let i = 0; i < arr.length; i++) {if (item[arr[i]] == undefined) {break;} else {item = item[arr[i]];if (i == arr.length - 1) {value = item;}}}return value;}

