1

In javascript, chrome console:

var test = [0, 1, 2, 3, 4]
> undefined
var lastIdx = --test.length
> undefined
lastIdx
> 4
test
> [0, 1, 2, 3]
var lastIdx = --(test.length)
> undefined
lastIdx
> 3
test
> [0, 1, 2]

As you already saw, I just want to get the last index of the array through the --array.length, but unfortunately the last element of the array get removed unexpectedly, really cannot understand how come this can/should happen, can someone explain?

4
  • -- does not mean just "one less than this number". It also decreases whatever you apply it to. Commented Nov 17, 2016 at 3:39
  • as always, JS and his weird stuffs... Commented Nov 17, 2016 at 3:44
  • use var lastIdx = test.length - 1 Commented Nov 17, 2016 at 3:45
  • @felipsmartins - nothing weird about expected behaviour Commented Nov 17, 2016 at 4:00

1 Answer 1

3

--x decrements x and returns the new value. (x-- decrements x and returns the old value.) So --test.length reduces the length by 1.

If you just want to get last index without modifying the length, that would be test.length - 1.

Sign up to request clarification or add additional context in comments.

1 Comment

In other words, it's like saying array.length = array.length - 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.