所以,我有 2 個由產品組成的物件,主要的和次要的,我做了一個回圈搜索主要的,如果它沒有找到產品,它會從次要中洗掉,即使有 10它作業的產品,現在我有 1470 個產品,回圈在第 4 次重復停止并說 << Uncaught TypeError: Cannot read properties of undefined (reading 'name') >> ,這是代碼
function deleter(){
let main = main_products;
let secondary= secondary_products;
let i;
let counter = 0;
console.log(main);
console.log(secondary); // just to be sure the data is ok
for (i=0;i<1550;i ){
counter = 0;
while (secondary[i].name !== main[counter].name){
counter ;
if (counter === 1550){
break ;
} // i did this with break i dont know why i did though
}
if (secondary[i].name === main[counter].name){
console.log("found -> " secondary[i].name);
}
else {
console.log("did not find product -> " secondary[i].name " on the main database . . . ");console.log("initializing product deletion . . .");
console.log(secondary[i].id);
deletedata();
document.getElementById("delete").innerHTML = "Done ??";
}
}
}
當我回圈 10 個產品時,它每次都能正常作業。既然產品明顯更多,我還需要做其他事情嗎?
編輯
所以這些物件是這樣制作的,我從 woocommerce 獲取
[ {“id”:67537,“name”:“test 10”,“slug”:“”,“type”:“simple”,“status”:“draft”,“featured”:false,“catalog_visibility”: “可見”,“描述”:“
阿拉吉
\n", "short_description": "", "sku": "1230975071-1-1-1-1-1-1-1-1-1", "price": "123122", "regular_price": " 123123”,“sale_price”:“123122”} {“id”:67536,“name”:“test 9”,“slug”:“”,“type”:“simple”,“status”:“draft”, “特色”:假,“目錄可見性”:“可見”,“描述”:“阿拉吉
\n", "short_description": "", "sku": "1230975071-2", "price": "123122", "regular_price": "123123", "sale_price": "123122"}]
這是一張圖片
兩個物件都來自 woo
uj5u.com熱心網友回復:
問題是 - 您超出了產品陣列的范圍。它是由以下原因引起的:
- 您有 1470 個產品,但對于 (i = 0; i < 1550; i )迭代超過 1550 個。可以用for (i = 0; i < secondary.length; i )固定
- 沒有額外的檢查我們是否有下一個元素或不在 while 回圈中
所以我想固定和優化版本的代碼可能看起來像這樣:
const main_products = [{id: 1, name: 'blabla1'}, {id: 2, name: 'blabla2'}, {id: 3, name: 'blabla3'}];
const secondary_products = [{id: 2, name: 'blabla2'}, {id: 4, name: 'blabla4'}, {id: 5, name: 'blabla5'}];
deleter();
function deleter() {
let main = main_products;
let secondary = secondary_products;
for (let i = 0; i < secondary.length; i ) {
const productWeFound = main.find((product) => secondary[i].name === product.name);
if (productWeFound) {
console.log("found -> " secondary[i].name);
} else {
console.log("did not find product -> " secondary[i].name " on the main database . . . ");
console.log("initializing product deletion . . .");
console.log(secondary[i].id);
// deletedata();
// document.getElementById("delete").innerHTML = "Done ??";
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/491301.html
標籤:javascript
上一篇:(如果steametn),即使當我單擊按鈕時值為空,它也會洗掉專案
下一篇:從后端回圈串列
