我有這樣的陣列。
const cntry = ['Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 'Hungary', 'Turkey', 'Iceland', 'Ireland'];
我想從這個陣列中洗掉包含單詞“land”的元素,但是因為我正在研究“for回圈”,所以我想只使用“for”方法來洗掉它。
我試過這段代碼,但沒有用。“愛爾蘭”仍在陣列中。我哪里做錯了?
for (let i = 0; i < cntry.length; i ) {
if (cntry[i].includes('land')) {
cntry.splice(i, 1);
}
}
輸出:
(9) ['Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Germany', 'Hungary', 'Turkey', 'Ireland']
uj5u.com熱心網友回復:
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。由于陣列是零索引的,這意味著第一個元素是索引的0,你需要從陣列的長度減 1 開始增量。有 11陣列中的元素,因此最后一個元素被索引10。
let i = cntry.length - 1;
然后允許回圈whilei大于或等于>=0。換句話說,當i小于0時離開回圈:
i >= 0;
最后,. for 回圈增量更改發生在對回圈塊進行評估之后和下一次迭代之前。decrement i
i--
在“現實世界”中,您將使用非常適合您希望評估的代碼塊的回圈構造。由于您正在改變陣列,因此它更適合forEach回圈,因為它不依賴于維護增量/索引關系。也許這就是你的家庭作業的目的,告訴你什么時候 for 回圈不合適。
uj5u.com熱心網友回復:
您可以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)
}
}
uj5u.com熱心網友回復:
已經有一個利用現有陣列的更好答案,但這里有一個替代解決方案。
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492621.html
標籤:javascript 数组 循环 for循环
上一篇:應用佇列時自動在陣列中獲取垃圾號
