Does JavaScript support array/list comprehensions like Python?

前端 未结 8 2182
名媛妹妹
名媛妹妹 2020-12-01 11:31

I\'m practicing/studying both JavaScript and Python. I\'m wondering if Javascript has the equivalence to this type of coding.

I\'m basically trying to get an array

8条回答
  •  执念已碎
    2020-12-01 12:12

    It does have a poor mans version

    const string = '1234-5'
    
    const forbidden = '-'
    
    print([int(i) for i in str(string) if i not in forbidden])
    const result = string.split('').filter(char => char !== forbidden);
    console.log(result)
    

    In JS you can only iterate over single elements in array, so no extraction of multiple entries at a time like in Python.

    For this particular case you should use a RegExp to filter the string though.

提交回复
热议问题