Javascript 第二个+之后没有返回值;迭代
我不知道这有什么问题:Javascript 第二个+之后没有返回值;迭代,javascript,oop,Javascript,Oop,我不知道这有什么问题: var get_depth = function(item, depth) { if(item.parent_id !== null) { get_depth(get_item_by_id(item.parent_id),depth+1); } else { alert ("return: " + depth); return depth; }
var get_depth = function(item, depth) {
if(item.parent_id !== null) {
get_depth(get_item_by_id(item.parent_id),depth+1);
} else {
alert ("return: " + depth);
return depth;
}
};
警报消息总是抛出一个正确的深度,但我希望将值存储在其中的变量仅接受一次迭代(返回值=1)。在两次或多次迭代之后,我的变量的值未定义。我不明白。你错过了退货
var get_depth = function(item, depth) {
if(item.parent_id !== null) {
return get_depth(get_item_by_id(item.parent_id),depth+1);
} else {
alert ("return: " + depth);
return depth;
}
};
为什么不使用这种语法呢?我发现这样做更容易:
function get_depth(item, depth) {
if(item.parent_id !== null) {
return get_depth(get_item_by_id(item.parent_id),depth+1);
} else {
alert ("return: " + depth);
return depth;
}
}
这是因为每次都应返回值:
var get_depth = function(item, depth) {
if(item.parent_id !== null) {
return get_depth(get_item_by_id(item.parent_id),depth+1);
} else {
alert ("return: " + depth);
return depth;
}
};
你第一次怎么称呼它?嘿,谢谢你!虽然我不太明白这句话,但它是有效的。。。我看不出有什么不同。我把它放在一个var get_depth中,以保持我的源代码干净。这是作为对象一部分的方法调用。我明白了,这可能只是习惯的问题。方法可以是对象的一部分,即使它没有声明为变量。但正如我所说,两者都很好。