gpt4 book ai didi

javascript - D3 JS - 未捕获类型错误 : Cannot read property 'length' of undefined - seems related to data issue

转载 作者:行者123 更新时间:2023-11-28 07:43:07 25 4
gpt4 key购买 nike

我发现列出了几个此类性质的问题。所以我有同样的问题:D3 - 未捕获类型错误:无法读取未定义的属性“长度”。

这发生在第 42 行: d: lineFun(ds.monthlySales)

感激不尽的任何想法,

谢谢杰瑞

我的代码和json如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>fm</title>

<script src="d3.min.js"></script>

<link rel="stylesheet" href="FMstyle.css" />

</head>
<body>


<div class="pageHeading">Facilities Management</div><br />

<script>
var h=100;
var w=400;
var ds; // global dataset variable
var salesTotal;
var salesAvg;
var metrics=[];

//function showHeader() {
// d3.select("#tree-container").append("h1")
// .text(ds.cat)
//}

function buildLine() {

var lineFun = d3.svg.line()
.x(function (d) { return d.month; })
.y(function (d) { return h-d.sales; })
.interpolate("linear");

var svg = d3.select("#tree-container").append("svg")
.attr({ width: w, height: h });


var viz = svg.append("path").attr({
d: lineFun(ds.monthlySales),
"stroke": "purple",
"stroke-width": 2,
"fill": "none"
});
}


d3.json("sales.json", function(error, data) {
if(error) {
console.log(error);
} else {
console.log("found some data");
console.log(data);
ds=data;
}

buildLine();
});

</script>

<div id="tree-container"
style="border: solid 1px blue; float: left;"></div>
<div style="border: solid 1px blue; width: 20%;
float: left; margin-left: 5px;">
<p>Properties</p>
<p>Properties</p>
<p>Properties</p>
</div>

</body>
</html>


[{ "content": [
{
"category": "Furniture",
"region": "West",
"monthlySales":
[{
"month":1,
"sales":38
},
{
"month":2,
"sales":40
},
{
"month":3,
"sales":41
},
{
"month":4,
"sales":39
},
{
"month":5,
"sales":43
},
{
"month":6,
"sales":35
}]
}]
}
]

最佳答案

JSON 的结构与您想要执行的操作不匹配。 lineFun需要一个数组但没有得到一个。轻松修复!

而不是:

ds=data;

用途:

ds=data[0].content[0].monthlySales;

这是一个有效的方法: http://plnkr.co/edit/Q9lfkY2Vc6g0rYYIAUKm?p=preview

如果您在浏览器中使用检查器,您可以看到生成的路径如下所示:

<path d="M1,62L2,60L3,59L4,61L5,57L6,65" stroke="purple" stroke-width="2" fill="none"></path>

但是路真的很短!

您可能想使用 d3.scale.linear 来标准化数据:

https://github.com/mbostock/d3/wiki/Quantitative-Scales

关于javascript - D3 JS - 未捕获类型错误 : Cannot read property 'length' of undefined - seems related to data issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27784895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com