我有下面的代碼。如果您將代碼傳遞給列表,它將提供該位置的值(它是零索引的)。此代碼有效,但如果我將count = count + 1與count ++(在條件的最後一個分支中),它不再有效。有人能幫我理解爲什麼嗎?爲什麼count ++在作爲參數傳遞時不起作用
注意:如果你這樣調用該函數:
var list = {value: 10, rest: {value: 10, rest: {value: 30, rest: null}}}
nth(list, 1)
輸出應該是20
function nth(list, index, count) {
if (count === undefined) {
count = 0;
}
if (count === index) {
return list.value;
}
else if (list.rest === null) {
return undefined;
}
else {
// note that count++ will not work here
return nth(list.rest, index, count = count + 1);
}
}
有你'list' – thefourtheye