这里是 d3.js 的新手。我试图访问每个数据的属性,但有些数据没有属性。当我尝试访问数据没有的属性时,我收到以下错误消息。
未捕获类型错误:无法读取属性
color(data[d.id][property])
var change = function() {
val = d3.event.target.value;
d3.selectAll("path").style("fill", function(d) {
// in this case val might be the property of the data[d.id], so that i
// want to escape this case.
color(data[d.id][val]); // data is a global variable
});
}
我的问题是如何简单地跳过对该特定属性的访问以避免此类型错误?
提前致谢。
最佳答案
有几种方法可以检查该属性是否存在。其中之一是使用 ternary operator :
d3.selectAll("path").style("fill", function(d) {
return data[d.id][val] ? color(data[d.id][val]) : "#ccc"
});
在那种情况下,如果属性存在,匿名函数将返回color(data[d.id][val])
,如果不存在,它将返回# ccc
(根据您的需要更改此颜色)。
关于javascript - 如何避免访问 d3.js 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43669317/