gpt4 book ai didi

javascript - 将++ 运算符应用于函数的返回值会导致错误

转载 作者:行者123 更新时间:2023-11-30 12:44:31 25 4
gpt4 key购买 nike

我必须遵循以下小测试页:

var getNum = function(){
return 5;
};
var y = getNum()++; // This causes an error.
document.write("y = " + y);

在 firefox 27.01 中导致此错误:

ReferenceError: invalid assignment left-hand side
var y = getNum()++;

如果我改变行:

var y = getNum()++;

对于

var y = getNum() + 1;

然后我就没有错误了。有人会碰巧知道为什么不允许 getNum()++ 吗?谢谢。

最佳答案

tldr:这没有意义。

++ 运算符(如 +=) 适用于 Reference Specification Type 的表达式.也就是说,++ 在与“变量或属性表达式”一起使用时有效。

The Reference type is used to explain the behaviour of such operators as delete, typeof, and the assignment operators [including ++, +=, etc]. For example, the left-hand operand of an assignment is expected to produce a reference [specification type expression].

这就是 JavaScript 如何将值赋值给适当的变量/属性。当无法进行此类赋值时,例如尝试将 ++ 应用于函数调用或文字表达式的结果时,将抛出运行时 ReferenceError。

(以上总结来自a previous answer of mine。)

关于javascript - 将++ 运算符应用于函数的返回值会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23069985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com