zhanglinjie_'s blog

By zhanglinjie_, history, 5 years ago, In English

In both python and JavaScript we can access the char of string with bracket:

in python

s = "abc"
s[0]
# it returns 'a'

in JavaScript

s = "abc"
s[0]
// it returns 'a'

But if we use the index -1 to get the last char

in python

s[-1]
# it returns 'c'

in JavaScript

s[-1]
# it returns undefined

Fortunately, we can simply use s[s.length - 1].

  • Vote: I like it
  • -28
  • Vote: I do not like it

»
5 years ago, hide # |
 
Vote: I like it +10 Vote: I do not like it

I prefer s.slice(-1)[0] if s is a long expression.