gpt4 book ai didi

Javascript:查找值在 JSON 中出现的次数

转载 作者:行者123 更新时间:2023-11-30 17:45:52 25 4
gpt4 key购买 nike

如果这是一个愚蠢的问题,我想原谅自己,但我无法弄清楚这里出了什么问题。我是 d3 的新手,老实说 Javascript 作为一个整体。我有一个看起来像这样的 json 文件:

[{"plaats":"AMSTERDAM","geboortejaar":1990,"vooropleiding":"MBO"}, {"plaats":"GENK","geboortejaar":1987,"vooropleiding":"HAVO"}, {"plaats":"JOPPE","geboortejaar":1992,"vooropleiding":"VWO"}]

我试图找出值“HAVO”、“MBO”和“VWO”在我的 JSON 文件中出现的频率。为此,我编写了以下代码:

var svgHeight = 400;
var svgWidth = 400;

var svg = d3.select("#pieChart")
.append("svg")
.attr("height", svgHeight)
.attr("width", svgWidth);

d3.json("propedeuse.json", function (error, json) {

alert("Hello, " + json[2]);

var VWO = 0,
HAVO = 0,
MBO = 0;

for (var i = 0; i <= json.length; i++) {

if (json[i].vooropleiding == "VWO") {
VWO++;
}

else if (json[i].vooropleiding == "HAVO") {
HAVO++;
}

else {
MBO++;
}
}

svg.append("p")
.text(HAVO);

console.log("MBO: " + HAVO);
console.log("HAVO: " + HAVO);
console.log("VWO: " + VWO);

});

我确实收到警报,“你好,[object Object]”。但是根据我的控制台,json[i] 是未定义的。为什么它突然未定义,而它在警报下工作得很好?

我需要做的(在这个例子中)是让控制台为每个值记录 1。

最佳答案

http://jsfiddle.net/jL2We/1/

var data = [{"plaats":"AMSTERDAM","geboortejaar":1990,"vooropleiding":"MBO"}, {"plaats":"GENK","geboortejaar":1987,"vooropleiding":"HAVO"}, {"plaats":"JOPPE","geboortejaar":1992,"vooropleiding":"VWO"}];

// Inside d3.json, your "json" variable is equivalent to this "data"

var vwo = data.filter(function(d) { return d.vooropleiding === "VWO"; }).length,
havo = data.filter(function(d) { return d.vooropleiding === "HAVO"; }).length,
mbo = data.filter(function(d) { return d.vooropleiding === "MBO"; }).length;

document.getElementById("vwo").innerText = vwo;
document.getElementById("havo").innerText = havo;
document.getElementById("mbo").innerText = mbo;

我同意@Jonah。这只是一个 JavaScript 问题。这是另一种方法。

关于Javascript:查找值在 JSON 中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198252/

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