首页 > 解决方案 > 检查属性是否存在于对象中或不存在于 JavaScript 中?

问题描述

我有一个问题陈述。

实现一个函数 propertyExists(obj, path),它接受一个对象和一个路径(字符串)作为参数,如果该属性在该对象上不存在或为空,则返回“False”,否则返回该属性的值。

这是解决方案。

function propertyExists(obj,path) {
    // Write logic here
    let result =  obj.hasOwnProperty(path);
    if(result)
    {
     return (obj.path);       
    }
    else
    {
        return result;        
    }
}

这是正确的做法吗?

标签: javascriptfunctionobject

解决方案


多个问题:函数的名字应该代表它在做什么,作为变量名的路径是模糊的,但作为变量的属性名是明确的。你应该做的是:

  1. 写函数调用,“getValue”它返回值,如果存在或null

    function getValue(obj,propertyName) {
            if(!obj) { // if object not exist
           return null;
            }
           return  obj[propertyName];
        }

  1. 编写函数调用,“propertyExists”如果存在则返回 true,否则返回 false。

   function propertyExists(obj,propertyName) {
        if(!obj) { // if object not exist
       return false;
        }
       return  obj.hasOwnProperty(propertyName);
    }
 


推荐阅读