Javascript 为什么count++;作为参数传递时不起作用
我有下面的代码。如果向代码传递一个列表,它将在该位置提供值(索引为零)。这段代码可以工作,但是如果我将count=count+1替换为count++(在条件的最后一个分支中),它将不再工作。有人能帮我理解为什么吗 注意:如果您这样调用函数:Javascript 为什么count++;作为参数传递时不起作用,javascript,arguments,increment,Javascript,Arguments,Increment,我有下面的代码。如果向代码传递一个列表,它将在该位置提供值(索引为零)。这段代码可以工作,但是如果我将count=count+1替换为count++(在条件的最后一个分支中),它将不再工作。有人能帮我理解为什么吗 注意:如果您这样调用函数: var list = {value: 10, rest: {value: 10, rest: {value: 30, rest: null}}} nth(list, 1) 输出应该是20 function nth(list, index, 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);
}
}
这是因为
count++
是后缀增量。这意味着它创建一个新值,即旧计数,并将该值传递给函数
你想要前缀
++count.
尝试改变
return nth(list.rest, index, count = count + 1);
到
您的
列表中没有20
,谢谢您的回答!
return nth(list.rest, index, ++count);