Javascript函数返回undefined而不是int
我的js/jquery函数不能正常工作,而不是INT返回未定义的Javascript函数返回undefined而不是int,javascript,jquery,recursion,Javascript,Jquery,Recursion,我的js/jquery函数不能正常工作,而不是INT返回未定义的 function __getLastSelectedCategory(table_id) { if ( jQuery('.categories_table[data-table-id="1"]').find('td.active').length > 0 ){ console.log('check1'); if (table_id != '0') { conso
function __getLastSelectedCategory(table_id) {
if ( jQuery('.categories_table[data-table-id="1"]').find('td.active').length > 0 ){
console.log('check1');
if (table_id != '0') {
console.log('check2');
var checkTableId = parseInt(table_id) - 1;
var table = jQuery('.cl_categories_display ').find('table[data-table-id="' + checkTableId + '"]');
if (table.find('td.active').length > 0) {
console.log('check3');
console.log('table id: ' + table.find('td.active').data('category-id'));
return table.find('td.active').data('category-id');
} else {
console.log('check4');
__getLastSelectedCategory(checkTableId);
}
} else {
console.log('check5');
var lastTable = jQuery('.cl_categories_display ').find('table:last');
var lastTableId = lastTable.data('table-id');
if (lastTable.find('td.active').length > 0) {
console.log('check6');
return lastTable.find('td.active').data('category-id');
} else {
console.log('check7');
__getLastSelectedCategory(lastTableId);
}
}
} else {
console.log('check8');
return null;
}
}
运行此功能时,我在控制台中看到:
检查1
支票5
支票7
检查1
支票2
支票3
表id:1
最后一只猫:未定义
因此,递归工作正常,但不是整数控制台打印表id:1,而是返回未定义的ir。可能有什么问题?您忘记了从递归调用返回值:它将值从内部函数返回到外部函数,但没有从外部函数返回到调用方。试试这个:
function __getLastSelectedCategory(table_id) {
if ( jQuery('.categories_table[data-table-id="1"]').find('td.active').length > 0 ){
console.log('check1');
if (table_id != '0') {
console.log('check2');
var checkTableId = parseInt(table_id) - 1;
var table = jQuery('.cl_categories_display ').find('table[data-table-id="' + checkTableId + '"]');
if (table.find('td.active').length > 0) {
console.log('check3');
console.log('table id: ' + table.find('td.active').data('category-id'));
return table.find('td.active').data('category-id');
} else {
console.log('check4');
return __getLastSelectedCategory(checkTableId);
}
} else {
console.log('check5');
var lastTable = jQuery('.cl_categories_display ').find('table:last');
var lastTableId = lastTable.data('table-id');
if (lastTable.find('td.active').length > 0) {
console.log('check6');
return lastTable.find('td.active').data('category-id');
} else {
console.log('check7');
return __getLastSelectedCategory(lastTableId);
}
}
} else {
console.log('check8');
return null;
}
}
您没有返回递归调用的结果。那么问题出在哪里?因为你只是输入了它,没有任何信息。你的意思是什么;不,兄弟。正如您在第三次检查后看到的,它返回表check 3:table ID:1的me ID,并且如果您在没有显式返回语句的情况下退出函数,则递归将停止—这将发生在代码进行递归调用的情况下—返回值将是未定义的。你不必相信我,但你只要几秒钟就可以试一下,