We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
const getAttribute = (object /*目标对象*/,attribute /*目标属性*/, defaultValue /*默认值*/) 示例: const obj = {a: {b: {c: 100}}, d:[{f: 'abc'}]}; getAttribute(obj, 'a.b.c', 0) === 100 getAttribute(obj, 'a.b.e', 'default') === 'default' getAttribute(obj, 'd.0.f') === 'a.b.c'
The text was updated successfully, but these errors were encountered:
思来想去,还是直接上来的简单,加了一丢丢脑补:
const getAttribute = (obj, attr, defaultValue = undefined) => { if(typeof attr === 'number' || typeof attr === 'symbol') { // 数字或 Symbol 属性 // 题目没讲,视为合法 if(attr in obj) return obj[attr]; } else if (attr && typeof attr === 'string') { // 字符串属性 // 题目没讲,那么空的 attr 视为不合法 let temp = obj; for(const a of attr.split('.')){ // 按“.”分割 if(!(a in temp)) return defaultValue; else temp = temp[a]; } return temp; } else return defaultValue; // 属性不合法或没有这个属性则返回默认值 };
测试用的代码:
{ const getAttribute = (obj, attr, defaultValue = undefined) => { if(typeof attr === 'number' || typeof attr === 'symbol') { // 数字或 Symbol 属性 // 题目没讲,视为合法 if(attr in obj) return obj[attr]; } else if (attr && typeof attr === 'string') { // 字符串属性 // 题目没讲,那么空的 attr 视为不合法 let temp = obj; for(const a of attr.split('.')){ // 按“.”分割 if(!(a in temp)) return defaultValue; else temp = temp[a]; } return temp; } else return defaultValue; // 属性不合法或没有这个属性则返回默认值 }; // 示例 const obj = {a: {b: {c: 100}}, d:[{f: 'abc'}], 1: 1, y: undefined}; console.log( getAttribute(obj, 'a.b.c', 0) === 100, getAttribute(obj, 'a.b.e', 'default') === 'default', getAttribute(obj, 'd.0.f') === 'abc', // 数字属性 getAttribute(obj, 1) === 1, // 使用 in 关键字因此不会忽略值为 undefined 的属性 getAttribute(obj, 'y', null) === undefined, ) }
回过头来看看,我写的这个还是有问题,没有考虑到属性名中可能出现.(英文句点)的情况, 题目没讲就当不存在咯 ;将typeof attr缓存一下也许更容易阅读 (用isNumber之类的类型守卫可以更好看) ,懒得改了。
.
typeof attr
isNumber
Sorry, something went wrong.
No branches or pull requests
The text was updated successfully, but these errors were encountered: