【问题标题】:Check property exist in object or not in JavaScript?检查属性是否存在于对象中或不存在于 JavaScript 中?
【发布时间】:2021-12-27 11:06:12
【问题描述】:

我有一个问题陈述。

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

这是解决方案。

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

这是正确的做法吗?

【问题讨论】:

  • 您是否面临与此实施有关的任何类型的问题?
  • 这取决于路径的定义是什么,对我来说,路径类似于..header.customer.address.lines[0] 等。但是你称之为propertyExists,所以它很可能是属性,所以不知道为什么不是propertyExists(obj, property) 你可能也想要return obj[path]
  • 根据要求,检查似乎不完整。你可以在这里具体一点。 -> if (obj[path] === undefined || obj[path] === null) { return false; } else { return obj[path]; }
  • @SifatHaque 是的,当我提交解决方案时,我收到了错误的回复消息

标签: javascript function object


【解决方案1】:

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

  1. 编写函数调用,“getValue”如果存在则返回值或为空

    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);
    }
 

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多