TypeError: Cannot call method 'forEach' of undefined " in d3 js on MVC Razor

回眸只為那壹抹淺笑 提交于 2019-12-25 02:48:13

问题


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:


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;
    });


来源:https://stackoverflow.com/questions/21987211/typeerror-cannot-call-method-foreach-of-undefined-in-d3-js-on-mvc-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!