我正在嘗試列出一份清單雜貨清單,并根據您已有的東西進行檢查,然后將其放入新清單中。我正在學習如何遍歷串列,但無法弄清楚為什么我會得到我的輸出。我希望輸出是在您已有的東西串列中找不到的東西的串列。目前的輸出會多次列印出我需要的內容。不知道為什么。謝謝
let groceryList = ['Bread', 'Cereal', 'Bagels', 'Water', 'Apple'];
let currentGrocery = ['Eggs', 'Lettuce', 'Milk', 'Cheese','Bread','Water','Oil'];
let newList = [];
for (let i = 0; i < groceryList.length; i ) {
for (let j = 0; j < currentGrocery.length; j ){
if (groceryList[i] !== currentGrocery[j]){
newList.push(groceryList[i]);
}
}
}
console.log(newList);
uj5u.com熱心網友回復:
let groceryList = ['Bread', 'Cereal', 'Bagels', 'Water', 'Apple'];
let currentGrocery = ['Eggs', 'Lettuce', 'Milk', 'Cheese','Bread','Water','Oil'];
let newList = [];
currentGrocery.forEach(item =>{
if (!groceryList.includes(item)) newList.push(item);
})
console.log(newList);
uj5u.com熱心網友回復:
您從您的購物清單中為每個不匹配的當前雜貨推送商品。您要做的是僅在當前沒有雜貨匹配項時才推送到新串列。
以一種天真的方式,這可以通過
let found = false;
for (let i = 0; i < groceryList.length; i ) {
for (let j = 0; j < currentGrocery.length; j ){
if (groceryList[i] == currentGrocery[j]){
found = true;
break;
}
}
if (found) {
newList.push(groceryList[i]);
found = false;
}
}
一種更具可讀性的方法是使用filter()和includes()函式:
let newlist = groceryList.filter(item => !currentGrocery.includes(item));
console.log(newlist);
uj5u.com熱心網友回復:
您可以過濾陣列。
const
groceryList = ['Bread', 'Cereal', 'Bagels', 'Water', 'Apple'],
currentGrocery = ['Eggs', 'Lettuce', 'Milk', 'Cheese', 'Bread', 'Water', 'Oil'],
newList = currentGrocery.filter(item => !groceryList.includes(item));
console.log(...newList);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/351009.html
標籤:javascript
下一篇:如何在本機反應中發出POST請求
