簡體   English   中英

如何檢查:數組是否正確包含特定文本?

[英]how to check: if array includes specific text properly?

我正在努力進行數組搜索,其中包含一段必須包含反斜杠的文本。 我試過includes(''); 否定includes(''); 並嘗試使用indexOf('')類似操作。

我有一個簡單的數組,最多有四個值; 通常它有兩個,這是它的典型外觀:

{tks: Array(2)}
tks: Array(2)
0: "https://mycoolwebsite.net/arcgis/rest/services"
1: "https://mycoolwebsite.com/arcgis/rest/services"
length: 2
__proto__: Array(0)
__proto__: Object

以下是我正在嘗試做的簡單檢查: 我對*includes* 'wdt'文本的第二次檢查似乎有效,所以我認為它是帶有反斜杠的東西。 反正我能應付嗎? 我感到困惑,為什么我ifelse都被打到下面用反斜杠第一次檢查。我加上了否定的else雙重檢查..有和沒有,在elseelse總是擊中。

    // right before doing the search I am building the array, just to add more context

    for (let i = 0; i < coolObj.length; i++) {
      if (coolObj[i].url){
          tr = coolObj[i].url;
          tks.push(tr);

          console.log({tks});     
       }
     }

    console.log({tks}); // consoles as I have included above ^

    if (tks.includes('/arcgis/rest/services')) {
            
      console.log({tks});     

    } else if (!tks.includes('/arcgis/rest/services')) { 

      console.log({tks});

      console.log('does not include correct url');
      aT = '/arcgis/rest/services';
      lP = false;
      filterAt(aT);
    }
    if (tks.includes('wdt')) {
      console.log({tks});

    }else {
      console.log({tks});
      wT = 'wdt';
      filterWt(wT);
    }

來自MDN 文檔includes() 方法確定數組是否在其條目中包含某個值,並根據需要返回 true 或 false。

您必須在數組元素中使用String.prototype.includes測試字符串,因此:

 const arr = ["https://mycoolwebsite.net/arcgis/rest/services", "https://mycoolwebsite.com/arcgis/rest/services"]; arr.forEach(el => { if (el.includes('/arcgis/rest/services')) { console.log(el, ': includes url'); } else { console.log('does not include correct url'); } if (el.includes('wdt')) { console.log(el, ': includes wdt'); } else { console.log('does not include correct wdt'); } });

暫無
暫無

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

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