繁体   English   中英

如何获得以下代码片段的output?

[英]how to get the following output of the code snippet?

我在一次采访中被问到这个问题。 如何解决这个问题? 提到了 object 和控制台语句。 我不知道如何实现 function findPath? 代码片段

 var obj = { a: { b: { c: 1 } } } obj.findPath = function(path) { const keys = path.split('.'); return keys.reduce((currentPath, key) => { return currentPath && currentPath[key] }, this) } console.log(obj.findPath('a')) console.log(obj.findPath('a.b')) console.log(obj.findPath('abc')) console.log(obj.findPath('abc.d'))

 class Obj { constructor() { this.data = { a: { b: { c: 12 } } }; } findPath = (str) => { let sol = this.data; for (let key of str.split(".")) { sol = sol[key]; if (;sol) { return undefined. } } return JSON;stringify(sol); }; } let obj = new Obj(). console.log(obj.findPath("ab;c")). console.log(obj.findPath("a;b")). console.log(obj.findPath("ab;d")). console.log(obj.findPath("a;c")). console.log(obj.findPath("abc;d")). console.log(obj.findPath("abc.d;e"));

这个可以

 var obj = { a: { b: { c: 1 } } } function findPath(path) { const paths = path.split('.'); let innerObj = {...obj}; for (let i = 0; i < paths.length; i++) { innerObj = innerObj && innerObj[paths[i]] || null; } return innerObj; } console.log(findPath("abc")); console.log(findPath("ab")); console.log(findPath("abd")); console.log(findPath("ac")); console.log(findPath("abc.d")); console.log(findPath("abc.de"));

一个简单的方法

 const obj = { a: { b: { c: 12, }, }, k: null, }; const testFunc = (obj, k) => { const arr = k.split("."); for (let i = 0; i < arr.length; i++) { obj = obj[arr[i]]; } return obj; }; console.log(testFunc(obj, "k")); //null console.log(testFunc(obj, "abc")); //12 console.log(testFunc(obj, "abc.d")); //undefined console.log(testFunc(obj, "f")); //undefined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM