zhanglinjie_'s blog

By zhanglinjie_, history, 4 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].

Full text and comments »

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

By zhanglinjie_, history, 4 years ago, In English

When you want to check is a number even, a simple way is compare the last bit with 0.

In Python you can write:

>>> 42 & 1 == 0
True

But in JavaScript you should take care about operator precedence

42 & 1 == 0
// returns 0

(42 & 1) == 0
// returns true

MDN has a detailed document about all precedence of operators in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table

Full text and comments »

  • Vote: I like it
  • +11
  • Vote: I do not like it

By zhanglinjie_, history, 4 years ago, In English
const arr = [10, 11, 9]

arr.sort() // it returns [10, 11, 9] because element be covert to string before sorting

arr.sort((a, b) => a - b)) // it returns [9, 10, 11], you MUST SPECIFY THE COMPARE FUNCTION when sorting numbers

Full text and comments »

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

By zhanglinjie_, history, 4 years ago, In English
'abc'.match(/[a-z]/g)
// this returns a array with three element

'abc'.match(/[1-9]/g)
// this returns null. BUT I EXPECTED A EMPTY ARRAY JUST LIKE OTHER NORMAL LANGUAGE TvT

Full text and comments »

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