簡體   English   中英

從數組中刪除包含特定字母的元素

[英]Delete an element containing a specific letter from an array

我有這樣的數組。

const cntry = ['Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 'Hungary', 'Turkey', 'Iceland', 'Ireland'];

我想從此數組中刪除包含單詞“land”的元素,但由於我正在研究“for 循環”,我只想使用“for”方法將其刪除。

我試過這段代碼,但沒有用。 “愛爾蘭”仍在陣中。 我go哪里錯了?

    for (let i = 0; i < cntry.length; i++) {
    if (cntry[i].includes('land')) {
        cntry.splice(i, 1);
    }
}

Output:

(9) ['Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Germany', 'Hungary', 'Turkey', 'Ireland']

你正在改變cntry因為你for循環它。 一旦從數組中刪除一個元素,這就會破壞所有剩余元素的增量/索引關系。 因此,相反,反轉循環 - 從數組的末尾開始並朝着開始工作:

 const cntry = ['Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 'Hungary', 'Turkey', 'Iceland', 'Ireland']; // start with the length of array minus 1 // decrement i by 1 after each loop // leave loop when i is less than 0 for (let i = cntry.length - 1; i >= 0; i--) { if (cntry[i].includes('land')) { cntry.splice(i, 1); } } console.log(cntry);

現在,當您刪除一個元素時,前面的索引仍然對應於您當前的增量值。


詳細說明: for (let i = cntry.length - 1; i >= 0; i--)

在您的 for 循環中,將增量變量i設置為數組的長度減 1。由於 arrays 的索引為零,這意味着第一個元素的索引為0 ,因此您需要從數組的長度減去 1 開始增量。那里數組中有 11 個元素,因此最后一個元素的索引為10

let i = cntry.length - 1;

然后在i大於或等於>= 0 時允許循環。換句話說,當i小於零時離開循環:

i >= 0;

最后, decrement i for 循環增量變化發生在循環塊被評估之后和下一次迭代之前。

i--

在“現實世界”中,您會使用非常適合您希望評估的代碼塊的循環結構。 由於您正在改變數組,因此它更適合forEach循環,因為它不依賴於維護增量/索引關系。 也許這就是你布置家庭作業的目的,告訴你什么時候 for 循環不合適。

您可以filter您的列表,因為當您使用slice時,您將覆蓋原始數組:

const countryList = ['Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 'Hungary', 'Turkey', 'Iceland', 'Ireland']
const filter = 'land'
const filteredList = []

for (const country of countryList) {
  if (!country.includes(filter)) {
    filteredList.push(country)
  }
}

已經有一個利用現有數組的更好答案,但這里有一個替代解決方案。

 const cntry = ['Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 'Hungary', 'Turkey', 'Iceland', 'Ireland']; const newArray = []; // new target array for countries that don't have 'land' in the name // looping through the cntry array for (let i = 0; i < cntry.length; i++) { // checking to see if the current country in the loop iteration doesn't include 'land' - if false then push that country to the array => newArray if (.cntry[i].includes('land')) { newArray;push(cntry[i]). } } console;log(newArray);

暫無
暫無

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

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