首页 > 解决方案 > 验证 var 是否存在

问题描述

我有一个不同条件的价值客户:

对于第一个和第二个条件,我的 json 结构是这样的:

json:
  fields:
    customer [1]:
      0 {3}:
        self: aaa
        value: yes
        id: 111

对于最后一个条件,我的 json 结构是这样的:

json:
  fields:
    customer:null

我正在尝试做这样的事情:

var customer = json.fields.customer[0].value ;  
    var score3 = 0;
        if(typeof customer == 'string'){          
            if(customer === "Yes"){
                score3 = +10;
            }
            else if(customer === "No"){
                score3 = +5;
            }
        }
        else{
            score3 = 0;
        }

但是我有一个问题说:“无法读取属性'0'”

我需要使用:

谢谢你的帮助

标签: javascriptjson

解决方案


我试图重现你的代码。有效。

更新了我创建了一个带有对象输入和输出分数的函数,您可以重复使用它。

function score(json){
var customer = json.fields.customer != null && json.fields.customer.length > 0 ? json.fields.customer[0].value : null;

    var score3 = 0;
        if(typeof customer == 'string'){          
            if(customer === "Yes"){
                score3 = +10;
            }
            else if(customer === "No"){
                score3 = +5;
            }
        }
        else{
            score3 = 0;
        }
        return score3;
}

//console.log(json);
function score(json){
var customer = json.fields.customer != null && json.fields.customer.length > 0 ? json.fields.customer[0].value : null;
//console.log(customer)
    var score3 = 0;
        if(typeof customer == 'string'){          
            if(customer === "Yes"){
                score3 = +10;
            }
            else if(customer === "No"){
                score3 = +5;
            }
        }
        else{
            score3 = 0;
        }
        return score3;
}

var json = {
  fields:{
     customers:null
  }
};
        
console.log(score(json));

json = {
  fields:{
     customer:[{
      id: 1,
      value: 'Yes'
     }]
  }
};
//console.log(json)
console.log(score(json));

json = {
  fields:{
     customer:[{
      id: 1,
      value: 'No'
     }]
  }
};
console.log(score(json));


推荐阅读