[英]Incrementing the result of Map.get()
I get the following error when trying to increment a value obtained from a map in the console in Chrome (50.0.2661.86): 尝试增加从Chrome(50.0.2661.86)控制台中的地图获取的值时出现以下错误:
Uncaught ReferenceError: Invalid left-hand side expression in postfix operation(…)
And similar in Node (4.4.3): 在Node(4.4.3)中类似:
ReferenceError: Invalid left-hand side expression in postfix operation
at repl:1:3
at REPLServer.defaultEval (repl.js:262:27)
at bound (domain.js:287:14)
at REPLServer.runBound [as eval] (domain.js:300:12)
at REPLServer.<anonymous> (repl.js:431:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:211:10)
at REPLServer.Interface._line (readline.js:550:8)
at REPLServer.Interface._ttyWrite (readline.js:827:14)
The offending code is: 违规代码是:
var m = new Map()
m.set(1, 0)
m.get(1)
var n = m.get(1)++ // Uncaught ReferenceError: Invalid left-hand side expression in postfix operation(…)
The following also fail: 以下也失败了:
var n = ++m.get(1)
var n = ++(m.get(1))
A bug in V8 maybe? 可能是V8中的一个错误? Or a misunderstanding in what's happening syntax-wise with the ++
operator? 或者误解了++
运算符在语法方面发生了什么?
I'm not an expert in JS evaluation scheme, but here's my try at explaining that. 我不是JS评估方案的专家,但是我试着解释一下。
In JS, (1)++
is invalid; 在JS中, (1)++
无效; you can't change a value . 你无法改变一个价值 。 What you can do is change a value attribution to a name: 您可以做的是将值归因更改为名称:
var a = 1;
a++;
In this case the value of 1
doesn't change; 在这种情况下,值1
不会改变; what changes is that a
now points to a different value. 什么样的变化是a
现在指向不同的值。
Similarly, you can't increment a value returned by .get()
; 同样,您不能增加.get()
返回的值; you need to convert it to a named expression before you can change that . 您需要先将其转换为命名表达式,然后才能更改它 。
In C++ terms we would say that ++
needs an lvalue , but the function return is an rvalue . 在C ++术语中,我们会说++
需要一个左值 ,但函数返回是一个右值 。
You can't assign a value to a function call. 您不能为函数调用赋值。 That would be like saying 那就像说
m.get(1) = m.get(1) + 1
You need to split this into two statements: 您需要将其拆分为两个语句:
const n = m.get(1) + 1;
m.set(1, n);
Or: 要么:
const n = m.get(1);
m.set(1, n++);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.