Skip to main content

Python vs JS

Python vs JS

REF

JSの優れた演算子の使いかたと足りない関数の代用のメモです。内包表記など、自分がよくつかう(忘れる)かき方をPythonと比べました。 以下では次の変数a,b,c,dを共通して用います。

  • List

    a = [1,2,3]

  • List

    b = [4,5,6]

  • Int

    c = 4

  • Dict

    d = {'a':a,'b':b}

e.g. spread operator

  • Python

    JS

  • a + b + [c]

    [...a, ...b, c]

  • {**d, 'c':c, **dict(d=0)}

    {...d, c, ...{d:0}}

  • (*,...はshallow copyなので注意)

basic Python vs JS

  • Python

    JS

  • 50//c*c

    ~~(50/c)*c //48 (c=4)

  • True if c>0 else c

    c>0 || c

  • c if c>0 else False

    c>0 && c

  • value, _, _ = a

    var [value, _, _] = a

  • func = lambda v: v*2

    func = v => v*2

  • bool = b[0]==c

    bool=b[0]===c : 値の一致

  • bool = a==b

    bool=!a.map((v,i)=>v===b[i] ).includes(false) 配列の一致(jsでは配列は===できない)

array Python vs JS

  • Python

    JS

  • sum(a)

    a.reduce((x,y)=>x+y)

  • max(a)

    a.reduce((x,y)=>x>y?x:y) //x<y?でmin

  • map(lambda: v**2, a)

    a.map(v=>v**2)

  • [0]*c

    Array(c).fill(0) // [0, 0, 0, 0]

  • [i for i in range(c)]

    [...Array(c)].map((_,i)=>i) //[0,1,2,3,4]

  • [v for v in zip(a,b)]

    a.map((v,i)=>[v,b[i]])

  • [[k,v] for k,v in d.items()]

    Object.keys(d).map((v,i)=>[v,Object.values(d)[i]])

class-based vs functional

class X extends React.Component{...}

const X=(props)=>{...}

  • access to state? : Yes

    Yes

  • lifecycle hooks ? : Yes

    No

  • acess state via ?: this.state

    useState

  • acess props via ?: this.props

    props

  • when use which?: use lifecycle or state<=> other

more

  • init delays via? : componentDidMount

    useEffect(()=>{...}, [])

  • run delays via? : componentDidUpdate

    useEffect(()=>{...},[...])

  • clean up via? : commponentWillUnmount

    useEffect(()=>{return()=>{...}}, [])

  • optimize via? : shouldCommponentUpdate

    useMemo and useCallback