TypeError: Cannot call method 'forEach' of

2019-08-30 20:54发布

Why I am getting error on below code in place of data.forEach I added D3 js as well but code is not able to identified the "data.forEach".please let me know how to resolve this issue on MVC razor.

my data2.csv is below

date,close
1971,0.357
1972,1.927
1973,1.870
1974,2.014
1975,10.995
1976,16.227
1977,16.643
1978,20.644
1979,22.478

my scripts is below

       var margin = { top: 20, right: 20, bottom: 30, left: 50 },
        width = 600 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

    var parseDate = d3.time.format("%Y").parse;

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var line = d3.svg.line()
        .x(function (d) { return x(d.date); })
        .y(function (d) { return y(d.close); });

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.csv("data2.csv", function (error, data)
    {
        data.forEach(function (d)
        {
            d.date = parseDate(d.date);
            d.close = +d.close;
        });


        x.domain(d3.extent(data, function (d) { return d.date; }));
        y.domain(d3.extent(data, function (d) { return d.close; }));

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text("million Sm3");

        svg.append("path")
            .datum(data)
            .attr("class", "line")
            .attr("d", line);
    });

</script>

1条回答
来,给爷笑一个
2楼-- · 2019-08-30 21:12

According to the comments above, it has to do with the parsing of the date and perhaps with the loading of the csv, as Lars suspects. In any case, here is a working fiddle after changing the csv to a javascript variable.

data.forEach(function (d)
    {
        d.date = parseDate(d.date.toString());
        d.close = +d.close;
    });
查看更多
登录 后发表回答