javascript 如何在 d3 方法链中有效地将数据从字符串转换为 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15704128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I efficiently convert data from string to int within a d3 method chain?
提问by microbug
I'm making an interactive bar chart in d3, and have come across a problem. The bar chart reads data from a form, but it reads the data as a string. When I am using the data to draw bars like this:
我正在 d3 中制作交互式条形图,但遇到了问题。条形图从表单中读取数据,但将数据作为字符串读取。当我使用数据绘制这样的条时:
var bars = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d,i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - (d * 4);
})
.attr("width", w / dataset.length - barPadding)
.attr("height", function(d) {
return d * 4;
})
.attr("fill", function(d) {
return "rgb(" + (d * redLevel) + ", 0, " + (d * blueLevel) + ")";
});
the data is read as a string. I could use parseInt(d)
every time I wanted to use d
, but that would be grossly inefficient. It would be easy to do var d = parseInt(d)
outside of the method chain, but that wouldn't work with d3. Suggestions?
数据作为字符串读取。parseInt(d)
每次我想使用时我都可以使用d
,但这会非常低效。var d = parseInt(d)
在方法链之外很容易做到,但这不适用于 d3。建议?
回答by Felix Kling
You could map the data before you bind it:
您可以在绑定数据之前映射数据:
.data(dataset.map(function(d) { return +d; }))
Then unary +
operator converts a numeric string into a number.
然后一元运算+
符将数字字符串转换为数字。