我正在创建对象数组,以在D3中创建图例。这些对象中的某些将具有特定的变量,而其他对象将不具有这些变量。相反,他们应该只使用默认值。
如何检查变量是否d.text
存在?我想这样做,而不是在所有使用默认值的对象中包含空字符串。
var size_link_data = [{
percentage : 0.5,
roundoff : 2,
recordType: 0,
text: "a calls b the most"
}, {
percentage : 0.5,
roundoff : 2,
recordType: 1,
text: ""
}, {
percentage : 0.3,
roundoff : 1,
recordType: 1,
text: ""
},
{
percentage : 0.1,
roundoff : 1,
recordType: 1,
text: ""
}
]
...
legened_next_section.append('text')
.attr('x', 35)
.attr('y', function (d, i) {
return i * 20; })
.text(function (d) {
return d.text != ""? d.text : d.percentage;
})
.style('fill', '#757575');
您可以检查该属性是否已定义。如果有,它将使用text
属性,否则将默认为percentage
。
.text(function (d) {
return typeof(d.text) !== "undefined" ? d.text : d.percentage;
})
在下面的例子中,typeof(size_link_data[0].text)
会string
而typeof(size_link_data[1].text)
返回undefined
。
var size_link_data = [{
percentage : 0.5,
roundoff : 2,
recordType: 0,
text: "a calls b the most"
}, {
percentage : 0.5,
roundoff : 2,
recordType: 1
//No 'text' property
}
];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句