Does JavaScript support array/list comprehensions like Python?

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

    Not directly, but it's not hard to replicate.

    var string = "1234-5";
    
    var forbidden = "-";
    
    string.split("").filter(function(str){
        if(forbidden.indexOf(str) < 0) {
            return str;
        }
    }).forEach(function(letter) { console.log(letter);});
    

    I guess more directly:

    for(var i=0 ; i < str.length ; i++) {
        if(forbidden.indexOf(str) < 0) {
            console.log(str[i]);
        }
    }
    

    But there's no built in way to filter in your for loop.

提交回复
热议问题