我对JS增量(++)有疑问。我知道很多人在这里询问JS中的++和+1差异,但没有人在递归调用句中提到它。
问题: 我想以递归方式调用exec函数内的函数exec,但是流动的脚本运行不正常。
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
Dim r As Long
On Error GoTo Skip:
'The below line ensures that the sheet change event will be triggered when a cell in colunm D is changed
'Change it as per your requirement.
If Not Intersect(Target, Range("D:D")) Is Nothing Then
Application.EnableEvents = False
r = Target.Row
If Cells(r, "A") = "Bravo" And Cells(r, "C") = "Gamma" Then
Target.Value = "Beta"
End If
End If
Skip:
Application.EnableEvents = True
End Sub
所以我将脚本更改为以下内容并且运行良好。
var exec = function(index){
if(index<7){
exec(index++);
}
}
exec(0);
output: Uncaught RangeError: Maximum call stack size exceeded
为什么它在这个例子中表现得有点不同?我的递归调用错了吗?
答案 0 :(得分:3)
Unhandled error in Deferred:
是后增量。这意味着它会增加变量,但表达式的值是旧值。所以:
index++
相当于:
exec(index++);
因此递归调用使用旧值,这意味着您继续使用相同的值递归调用,并且永远不会达到停止递归的限制。
您需要使用预增量,这会增加变量并返回 new 值:
var oldindex = index;
index += 1;
exec(oldindex);
实际上,根本没有理由增加变量,因为你从未在该函数中再次使用它。只是做:
exec(++index);
答案 1 :(得分:1)
index++
的问题在于它是一个后增量,所以它只会在之后递增index
的值,它已经被传递回{{1} }。使用预增量(exec
)应该有效,因为它会在将它传递给递归调用之前递增它。
++index