Does JavaScript support array/list comprehensions like Python?

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

    Reading the code, I assume forbidden can have more than 1 character. I'm also assuming the output should be "12345"

    var string = "12=34-5";
    
    var forbidden = "=-";
    
    console.log(string.split("").filter(function(str){
        return forbidden.indexOf(str) < 0;
    }).join(""))
    

    If the output is "1" "2" "3" "4" "5" on separate lines

    var string = "12=34-5";
    
    var forbidden = "=-";
    
    string.split("").forEach(function(str){
        if (forbidden.indexOf(str) < 0) {
            console.log(str);
        }
    });
    
    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题