javascript - 验证 var 是否存在
问题描述
我有一个不同条件的价值客户:
- 如果客户 = 是,那么得分 = 10
- 如果客户 = 否,则得分 = 5
- 如果客户为空,则得分 = 0
对于第一个和第二个条件,我的 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'”
我需要使用:
- json.fields.custom[0].value(1和2条件)
- json.fields.custom(最后一个条件)
谢谢你的帮助
解决方案
我试图重现你的代码。有效。
更新了我创建了一个带有对象输入和输出分数的函数,您可以重复使用它。
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));
推荐阅读
- java - TabLayout 迁移到 AndroidX
- python - 如何在python中的zip文件夹中创建文件?
- c++ - 如何在 Cython 中链接嵌套的 C++ 库
- javascript - 使用 laravel 中的 db 数据更改 tui-calender 中的数据
- reactjs - ReactJS D3 - 如何放大 D3 地理世界地图
- python - 如何在python中水平堆叠两个矩阵
- java - 使用 Maps Elevation API
- php - 在特定列上使用条件验证 Laravel
- angular - 在方法中动态获取组件并以角度设置其属性
- javascript - 类型错误:this.props.* 不是函数