繁体   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