在这段代码片段中递归是如何发生的?
查看调用堆栈和监视,现在当我按 F10 时,监视"中的行的值更改为对象对象",因此一切都发生了,我了解直到此时和之后发生的流程不清楚.现在在病房里,为什么即使我在第 8 行提供断点代码也不会停在第 8 行
Look at the call Stack and Watch, Now when i press F10, the line's value in "Watch" changes to be "object Object" and because of that everything happens, i understand the flow till this time and afterwards what happen is not clear. Now on wards, why does the code doesn't stop at line 8 even if I Provide a break point at line 8
这是关于stackoverflow
我正在尝试理解这段代码
I am trying to understand this code snippet
function assign(obj, prop, value) {
if (typeof prop === "string")
prop = prop.split(".");
if (prop.length > 1) {
var e = prop.shift();
assign(obj[e] =
Object.prototype.toString.call(obj[e]) === "[object Object]"
? obj[e]
: {},
prop,
value);
} else
obj[prop[0]] = value;
}
var obj = {},
propName = "foo.bar.foobar";
assign(obj, propName, "Value");
递归是如何发生的,因为函数没有返回任何东西?内部调用中的参数值如何随着最顶层调用堆栈(分配函数)中的函数而改变?
How recursion is happening, as the function is not returning anything ? How the value of the arguments in the inner call being changed as the function in the top most call stack(of assign function) is completed ?
感谢大家的回答,但我的确切问题是它在这一行(第 8 行)中是如何发生的.
Thanks all for answers but my exact question i how its happening in this particular line (line 8).
Object.prototype.toString.call(obj[e]) === "[object Object]"
永远不会为真.它总是 "[object Undefined]"
Object.prototype.toString.call(obj[e]) === "[object Object]"
is never true. It is always "[object Undefined]"
开头:
obj:: {}
prop:: 'foo.bar.foobar'
从内部函数(if
)第一次调用之前:
obj:: {foo: {}}
prop:: ['bar', 'foobar']
在第二次调用内部函数之前(if
):
obj:: {foo: {bar: {}}}
prop:: ['foobar']
最后执行时,因为 prop.length
为 1(else
- 不再递归):
At last execution, as prop.length
is 1 (else
- no more recursion):
obj:: {foo: {bar: {foobar: 'Value'}}}
prop:: []
Javascript 中的对象总是作为引用传递,参考@Tiny Giant 的评论.
Objects in Javascript are always passed as Reference, refer to @Tiny Giant's comment.