在 json object 上使用 $.each 语句时出现错误
When using an $.each statement on my json object I get an error
在我的 json object 上使用 $.each 语句时,我收到“未捕获的类型错误:无法读取未定义的 属性 'length'”。我知道我的 $.each 语句导致了它,因为当我按预期将 console.log returns [Object, Object, Object] 注释掉时。我想要做的是遍历 object 和 return 标题的值。
$(function () {
var MENU = [
{
'title': 'Item 1',
'submenu': null
},
{
'title': 'Item 2',
'submenu': null
},
{
'title': 'Item 3',
'submenu': [
{
'title': 'Sub 1',
'submenu': null
},
{
'title': 'Sub 2',
'submenu': null
},
{
'title': 'Sub 3',
'submenu': [
{
'title': 'SubSub 1',
'submenu': null
},
{
'title': 'SubSub 2',
'submenu': null
},
{
'title': 'SubSub 3',
'submenu': null
}
]
}
]
}
];
var getMenuItem = function (MENU) {
$.each(MENU, function (key, value) {
var title = value.title;
$('#myMenu').append('<ul>' +'<li>' + title +'</li>' + '</ul>' );
});
console.log(MENU);
};
getMenuItem();
console.log(MENU);
});
你的函数 getMenuItem
需要一个迭代的参数,但在你的调用中你没有传递任何参数,所以函数内部的 MENU
是未定义的,因此是错误的。
所以改变
getMenuItem();
到
getMenuItem(MENU);
如果您不想将菜单实例传递给函数并希望使用共享变量 MENU
然后从函数定义中删除参数声明,即将 var getMenuItem = function (MENU) {
更改为
var getMenuItem = function () {
//now here MENU will refer to the MENU variable in the shared scope
}
您必须更改函数调用或函数声明,因为它们不兼容。
申报变更如下:
var getMenuItem = function () { //removed unnecessary argument
或将调用更改为
getMenuItem(MENU) // pass MENU as argument
在我的 json object 上使用 $.each 语句时,我收到“未捕获的类型错误:无法读取未定义的 属性 'length'”。我知道我的 $.each 语句导致了它,因为当我按预期将 console.log returns [Object, Object, Object] 注释掉时。我想要做的是遍历 object 和 return 标题的值。
$(function () {
var MENU = [
{
'title': 'Item 1',
'submenu': null
},
{
'title': 'Item 2',
'submenu': null
},
{
'title': 'Item 3',
'submenu': [
{
'title': 'Sub 1',
'submenu': null
},
{
'title': 'Sub 2',
'submenu': null
},
{
'title': 'Sub 3',
'submenu': [
{
'title': 'SubSub 1',
'submenu': null
},
{
'title': 'SubSub 2',
'submenu': null
},
{
'title': 'SubSub 3',
'submenu': null
}
]
}
]
}
];
var getMenuItem = function (MENU) {
$.each(MENU, function (key, value) {
var title = value.title;
$('#myMenu').append('<ul>' +'<li>' + title +'</li>' + '</ul>' );
});
console.log(MENU);
};
getMenuItem();
console.log(MENU);
});
你的函数 getMenuItem
需要一个迭代的参数,但在你的调用中你没有传递任何参数,所以函数内部的 MENU
是未定义的,因此是错误的。
所以改变
getMenuItem();
到
getMenuItem(MENU);
如果您不想将菜单实例传递给函数并希望使用共享变量 MENU
然后从函数定义中删除参数声明,即将 var getMenuItem = function (MENU) {
更改为
var getMenuItem = function () {
//now here MENU will refer to the MENU variable in the shared scope
}
您必须更改函数调用或函数声明,因为它们不兼容。 申报变更如下:
var getMenuItem = function () { //removed unnecessary argument
或将调用更改为
getMenuItem(MENU) // pass MENU as argument