我正在尝试获取数据并在使用d3
绘制数字之前向数字添加变量然而,在javascript中使用+进行添加只是将变量号附加到数据编号而不是添加它?
var extraCash = 100
var budget= d3.format(",")(data[1].total_budget+extraCash);
数据如下:
{"rows":[["total_budget"],["200"]]},
预算应该是300,但我得到200,100
答案 0 :(得分:2)
看起来totalCash
是String
,请尝试强制:
var budget= d3.format(",")(Number(data[1].total_budget) + extraCash);
其他方法:
parseFloat(data[1].total_budget) + extraCash
parseInt(data[1].total_budget, 10) + extraCash
+ data[1].total_budget + extraCash /* <-- "unary" operator */
这些方法的行为都不同,可能导致意外结果。熟悉每种方法的细微差别是一个好主意。
https://developer.mozilla.org/en-US/docs/Glossary/Type_Conversion https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus