javascript - 检查属性是否存在于对象中或不存在于 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;
}
}
这是正确的做法吗?
解决方案
多个问题:函数的名字应该代表它在做什么,作为变量名的路径是模糊的,但作为变量的属性名是明确的。你应该做的是:
- 写函数调用,“getValue”它返回值,如果存在或null
function getValue(obj,propertyName) {
if(!obj) { // if object not exist
return null;
}
return obj[propertyName];
}
- 编写函数调用,“propertyExists”如果存在则返回 true,否则返回 false。
function propertyExists(obj,propertyName) {
if(!obj) { // if object not exist
return false;
}
return obj.hasOwnProperty(propertyName);
}
推荐阅读
- json - django REST框架,验证json数据
- pivot-table - 如何为季度数据创建数据透视表/图表?
- python-3.x - Python - 多处理池映射返回不能腌制错误
- swift - 在 Swift 4 中解开一个可选项
- javascript - Javascript导出表到excel UTF-8问题
- sql - 在嵌套情况下分组,条件在不同表上
- aforge - Aforge 视频画质
- c++ - 有哪些方法可以根据 256 位密钥对矩阵进行加扰?
- reactjs - 为什么我的 import (let) 对象是只读的?反应 JS
- karate - 空手道休息 API 测试:获取 com.intuit.karate - 找不到可运行的场景:class.feature,env:null