考虑answer response below关于。{ 参考ECMAScript Language Specification - 11.13.2 Compound Assignment
考虑为什么这些,
javascript:
o=""; o = o + (o+=1) ; alert(o);
o=""; o = (o+=1) + o; alert(o);
不一样。从左到右的脚本评估存在时间语义问题(参考:ECMA spec. - The addition operator)。一个结果是+
运算符不一定是可交换的。
这也可以通过以下方式看出:
javascript:
o=1; o = o + (o+=1) ; alert(o);
o=1; o = (o+=1) + o; alert(o);
或
javascript:
o=" _ "; o = o + (o+=1) ; alert(o);
o=" _ "; o = (o+=1) + o; alert(o);
懒惰的评估范式,由我错误地和不恰当地使用从而产生下面的问题,也是我个人工作方式的一个不好的属性。
以下考虑事项可能已经解决,但似乎没有。如果是这样,是否可以提供与讨论的链接?
Gecko Javascript运行时引擎的正式指称语义是一个谜。 经验测试令人筋疲力尽,无法详尽无遗。
参考资料ECMAScript Language Specification似乎不足,但为这些脚本的混合提供了信任,例如,
javascript: alert( function(){return {}}().life=42 )
在绑定值时具有此类构造的结果。
这将澄清呼叫的概念(或者更确切地说,使用)需求,价值,参考,推理,名称......作为相关与否。 Javascript是一个原型解释器,它给下面的一些问题隐含的意义。
预期结果是什么:
javascript: o={n:0}; f=function(){o.n+=1; return 10};
alert([
o.n, f(),
o.n, o.n+=f(),
o.n, eval('o.n+=f()'),
o.n, eval('o.n+='+f()),
o.n,
].join(",\t"));
?是否容易预测结果(正确!)?
这个问题有点夸夸其谈,因为它是eval
专门用来强迫和强调解释的微妙细微差别。是否可以使用前面提到的ECMAScript Language Specification或其他文档来解决此脚本(以及下面的旁边)的评估?
(另外,请考虑:
javascript: ra=[];
alert([
ra, ra[ra.length]=" partially defined.",
ra, ra.push("\n RA is not shown"),
ra, ra.reverse()[42],
].join(",\t\t"));
显示:
RA is not shown, partially defined., partially defined., RA is not shown, partially defined., 2, RA is not shown, partially defined.,
ra
的部分评估与o.n
不相似!
和以下比使用o.n:
更不具异国情调javascript: o=""; f=function(){o+=1; return 0};
alert([
o, f(),
o, o+=f(),
o, eval('o+=f()'),
o, eval('o+='+f()),
o,
].join(",\t"));
显示:
, 0, 1, 10, 10, 100, 100, 10010, 10010
)
考虑以下脚本:
javascript:
asn="\t\t and so now,\t o.n is "; nl="\n\n";
o={}; f=function(){o.n+=1; return 10};
alert(["Using:\n",window.navigator.userAgent,
nl,"The function f() is:\n ",f,
nl,"What the!!?!? \t\t\t\t\t\t\t initially \t\t o.n is ", o.n = 0,
nl,"Called as a procedure: \t\tf() is ", f(), asn, o.n,
nl,"but, instead of 12 \t\to.n+=f() is ", o.n+=f(), asn, o.n,
nl,"however eval'd\t\to.n+=f() is ", eval("o.n+="+f()), asn, o.n,
"!\n\nIt makes no functional difference if, instead of o.n, o['n'] is used.",
"\nThe expected o.n evaluation sequence is 0, 1, (+1+10=) 12, (+1+10=) 23.",
"\n_____ _____ _____ _____ _____ _____ _____ _____^^ missing in result",
].join(""));
Gecko引擎输出:
Using: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3 The function f() is: function () { o.n += 1; return 10; } What the!!?!? initially o.n is 0 Called as a procedure: f() is 10 and so now, o.n is 1 but, instead of 12 o.n+=f() is 11 and so now, o.n is 11 however eval'd o.n+=f() is 22 and so now, o.n is 22! It makes no functional difference if, instead of o.n, o['n'] is used. The expected o.n evaluation sequence is 0, 1, (+1+10=) 12, (+1+10=) 23. _____ _____ _____ _____ _____ _____ _____ _____^^ missing in result
答案 0 :(得分:1)
JavaScript在ECMA标准中明确规定了一个急切的评估(按值调用)执行模型。所有这些问题都可以通过阅读标准来解决。例如,在标准的11.13.2中清楚地说明了结果是11而不是12的原因。 o.n在调用f()之前进行评估,而不是按照步骤2的规定进行评估。