簡體   English   中英

這個 python function 的 javascript/typescript 等價物是什么?

[英]What is javascript/typescript equivalent of this python function?

我無法將此語法轉換為 js 或 ts:

    def get_index(self):
        path = self.get_request_path()
        if "/_async_search" in path and "/_search":
            # no index we wildcard
            return next((sub_part for sub_part in path.split("/") if sub_part != ""), "*")
        return None

我認為對 python 代碼進行 javascript 翻譯的主要困難是像在 python 代碼中那樣延遲加載path.split("/")返回的列表。

為此,您可以使用生成器 function,如下所示:

function* first_substring(path) {
  for(substring of path.split("/")){
    if(substring !== ""){
        yield substring;
    }
    else{
        yield "*";
    }
  }
}

那么您的 javascript 翻譯將類似於:

function get_index(){
    const path = this.get_request_path();

    if(path.indexOf("/_async_search") !== -1 && "/_search"){
        return first_substring(path).next().value;
    }

    return None

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM