鉴于这些csv
和year
,我将搜索suicide_no
文件中涉及自杀的数据。
我想总结一下每年自杀的总数。
我有以下代码:
d3.csv("master.csv", function(error,data){
if(error) console.log("Erro no ficheiro csv");
var years = [];
var suicides = [];
var taxaAno = new Object();
var taxaAno = {};
data.forEach(function(d){
years = +d.year;
suicides = +d.suicides_no;
if (taxaAno==null){
taxaAno[years]= suicides;
}
else{
taxaAno[years]+= suicides;
}
});
console.log(taxaAno);
});
我希望字典最后出现。但它看起来像这样:
{1985: NaN, 1986: NaN, 1987: NaN, 1988: NaN, 1989: NaN, 1990: NaN, 1991: NaN, 1992: NaN, 1993: NaN, 1994: NaN, 1995: NaN, 1996: NaN, 1997: NaN, 1998: NaN, 1999: NaN, 2000: NaN, 2001: NaN, 2002: NaN, 2003: NaN, 2004: NaN, 2005: NaN, 2006: NaN, 2007: NaN, 2008: NaN, 2009: NaN, 2010: NaN, 2011: NaN, 2012: NaN, 2013: NaN, 2014: NaN, 2015: NaN, 2016: NaN}
答案 0 :(得分:1)
您正在检查taxaAno
是null/undefined
而不是taxaAno[years]
。这意味着您总是会碰到这一行:
taxaAno[years]+= suicides;
因此,这是您第一次在suicides
上添加数字(undefined
)。应该是:
if (taxaAno[years] == null){
taxaAno[years] = suicides;
} else {
taxaAno[years]+= suicides;
}