[英]getJSON getting all items but has undefined error
I'm using getJSON
for my JSON data items, like this: 我将
getJSON
用于JSON数据项,如下所示:
$.getJSON(projects, function (json) {
var firstThree = json.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
.slice(0, 3);
var related = firstThree;
var i = '';
$.each(json, function(i) {
var sizeClass = JSON.stringify(related[i].pname);
console.log('sifzdfze'+sizeClass);
});
I checked on console, getting sizeClass item, it works. 我检查了控制台,获取sizeClass项目,它可以工作。 But but it also shows an error:
但是它也显示了一个错误:
related[i] is undefined
What's the problem? 有什么问题? Thanks!
谢谢!
As per your code you are accessing related
as an array. 根据你的代码,您正在访问
related
数组。 So you are supposed to iterate over the items in the array. 因此,您应该遍历数组中的项目。 In your case
related[i]
is undefined
because you are trying to access an item that is out of bounds of the particular array. 在您的情况下,
related[i]
是undefined
因为您正试图访问超出特定数组范围的项目。
$.each(json, function(i) {
supposed to be 应该是
$.each(related, function(val, i) {
Also the above line, creates an i
that is scoped to the each
callback. 同样在上面的行中,创建一个范围为
each
回调的i
。 So there is not need to declare it in the line above. 因此,无需在上面的行中声明它。 Here
val
is the current value in iteration whose index is i
. val
是迭代中的当前值,其索引为i
。 It can be simplified as 可以简化为
$.each(related, function(val, i) {
var sizeClass = JSON.stringify(val.pname);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.