以下是手写的 get
函数实现,用于安全地访问嵌套对象属性:
ini
javascript
function get(obj, path, defaultValue) {
// 将路径转换为数组形式
const pathArray = Array.isArray(path)
? path
: path.split(/.|$$|$$/).filter(p => p !== '');
let current = obj;
for (const key of pathArray) {
if (current === null || current === undefined) {
return defaultValue; // 遇到null/undefined立即返回默认值
}
current = current[key]; // 逐层访问属性
}
return current === undefined ? defaultValue : current;
}
实现说明:
-
路径处理
- 若
path
是数组,直接使用。 - 若
path
是字符串,按.
、[
或]
分割,并过滤空字符串。例如'a[0].b'
会被转换为['a', '0', 'b']
。
- 若
-
逐层访问属性
- 遍历路径数组,依次访问对象的属性。
- 若中间遇到
null
或undefined
,直接返回默认值。
-
返回值处理
- 最终值为
undefined
时返回defaultValue
,否则返回实际值。
- 最终值为
示例用法:
csharp
javascript
const obj = { a: { b: [ { c: 3 } ] } };
console.log(get(obj, 'a.b.0.c')); // 3
console.log(get(obj, ['a', 'b', '0', 'c'])); // 3
console.log(get(obj, 'a.x', 'default')); // 'default'
console.log(get(null, 'a.b')); // undefined
注意事项:
- 属性名含
.
或[]
时,需使用数组形式路径(如['a.b', 'c']
)。 - 若需支持更复杂的路径(如带引号的字符串),需扩展路径解析逻辑。