Does JavaScript support array/list comprehensions like Python?

前端 未结 8 2119
名媛妹妹
名媛妹妹 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:21

    Given the question's Python code

    print([int(i) for i in str(string) if i not in forbidden])
    

    this is the most direct translation to JavaScript (ES2015):

    const string = '1234-5';
    const forbidden = '-';
    
    console.log([...string].filter(c => !forbidden.includes(c)).map(c => parseInt(c)));
    // result: [ 1, 2, 3, 4, 5 ]

    Here is a comparison of the Python and JavaScript code elements being used: (Python -> Javascript):

    • print -> console.log
    • iterate over characters in a string -> spread operator
    • list comprehension 'if' -> Array.filter
    • list comprehension 'for' -> Array.map
    • substr in str? -> string.includes

提交回复
热议问题