JavaScript判断对象指定路径属性是否存在的实现是否正确?
propertyExists函数实现问题解答
你当前的实现不是正确的,存在以下几处核心问题,完全不符合需求要求:
- 不支持多级路径解析:需求中传入的
path是路径字符串,支持类似a.b.c的多层嵌套属性查询,但你现有代码仅用obj.hasOwnProperty(path)判断一级属性,完全无法处理嵌套场景。 - 属性取值语法错误:代码中
obj.path是固定读取对象上名为path的属性,而非读取path变量指向的属性名,正确的动态属性取值语法应为obj[path]。 - 返回逻辑不符合要求:需求规定属性不存在、或属性值为null时返回
False,其余场景返回属性值。你现有代码在属性不存在时直接返回hasOwnProperty的布尔值false,也没有额外判断属性值为null的场景,属性存在但值为null时会直接返回null而非要求的False。
正确实现参考
function propertyExists(obj, path) { // 拆分路径为属性数组,支持.分隔的多级路径 const keyList = path.split('.'); let currentValue = obj; for (const key of keyList) { // 当前层级不存在/不是对象/无对应属性,直接返回False if (currentValue === null || typeof currentValue !== 'object' || !currentValue.hasOwnProperty(key)) { return 'False'; } currentValue = currentValue[key]; } // 最终值为null也返回False,否则返回对应值 return currentValue === null ? 'False' : currentValue; }
测试用例示例
const demoObj = { user: { name: "张三", age: null, address: { city: "北京" } }, id: 1001 }; console.log(propertyExists(demoObj, 'user.name')); // 输出:张三 console.log(propertyExists(demoObj, 'user.age')); // 输出:False console.log(propertyExists(demoObj, 'user.address.city')); // 输出:北京 console.log(propertyExists(demoObj, 'user.phone')); // 输出:False console.log(propertyExists(demoObj, 'id')); // 输出:1001
内容的提问来源于stack exchange,提问作者Deepak _8097
相关产品推荐
相关产品推荐

