Вопрос

For looping variables (usually array indexes) I do a lot of pre-incrementing and modulus assigning in a loop. In other languages this would look like

++_index %= LENGTH;

(broken up version on multiple lines)

_index++;
_index = _index % LENGTH;

This of course increases the _index by 1 and then assigns the modulus back to itself.

but I have problems doing this in Javascript I get the horrible ReferenceError: Invalid left-hand side in assignment.

I suspect what it is actually doing is trying to do assign the modulus of a variable called "++_index" which of course, there is none as its invalid.

I tried using parentheses to hopefully have it read it has _index correctly but still this seemed to be a bust.

(++_index) %= LENGTH;

I have resorted to using the broken down version of

++_index;
_index %= LENGTH;

But I cannot find any documentation on the issue at hand. All my google-fu is bringing back people using = within if statements.

Could someone with far superior google-fu direct me to some documentation that can explain this in more depth. As I said, I suspect its trying to do the assignment to ++_index, rather than evaluate it, increment it and pass reference to variable for the next stage of assigning the modulus. But something (or someone) to confirm or deny this would be most beneficial.

Это было полезно?

Решение

The JavaScript prefix increment operator doesn't return a reference, it just returns a value. It's invalid to assign to a number, so that's why it throws a ReferenceError.

You either have to do this:

_index = ++_index % LENGTH;

or this:

++_index;
_index %= LENGTH;

Specification:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Let oldValue be ToNumber(GetValue(expr)).
  3. ReturnIfAbrupt(oldValue).
  4. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 12.7.5).
  5. Let status be PutValue(expr, newValue).
  6. ReturnIfAbrupt(status).
  7. Return newValue.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top