Javascript 为错误动态使用hasOwnProperty';无法读取属性'';未定义的';
我发现了错误 无法读取未定义的属性“billingDate”Javascript 为错误动态使用hasOwnProperty';无法读取属性'';未定义的';,javascript,undefined,hasownproperty,Javascript,Undefined,Hasownproperty,我发现了错误 无法读取未定义的属性“billingDate” response.detailsResponse.installment.billingDate 分期付款此处未定义 response.detailsResponse.installment.billingDate 我想使用hasOwnProperty,但是以一种动态的方式,就像我将路径和对象(要检查的对象)传递给函数一样,它执行以下检查并返回true或false function checkProperty(path, obj)
response.detailsResponse.installment.billingDate
分期付款此处未定义
response.detailsResponse.installment.billingDate
我想使用hasOwnProperty,但是以一种动态的方式,就像我将路径和对象(要检查的对象)传递给函数一样,它执行以下检查并返回true或false
function checkProperty(path, obj){
//assuming path = response.detailsResponse.installment.billingDate
//assuming obj = response [a json/object]
//check if response.detailsResponse exists
//then check if response.detailsResponse.installment exists
//then check if response.detailsResponse.installment.billingDate exists
}
路径长度/关键点可能会有所不同
代码必须经过优化和通用。您可以按以下方式重写函数
function checkProperty(path,obj){
splittedarr = path.split('.');
var tempObj = obj;
for(var i=1; i<splittedarr.length; i++){
if(typeof tempObj[splittedarr[i]] === 'undefined'){
return false;
}else{
tempObj = tempObj[splittedarr[i]];
}
}
return true;
}
功能检查属性(路径,obj){
splittedarr=path.split('.');
var tempObj=obj;
对于(var i=1;我非常感谢你。