arr.findIndex() returns -1
arr.findIndex() returns -1
恐怕这应该是显而易见的,因为我的事情是基于普通的 Vanille JS。无论如何,出于任何原因我无法解决我的问题。谁能帮帮我?
我在 reducer 中的代码快照:
> case TOGGLE_PRODUCT:
> const newProducts = [...state.allProducts];
> console.log("All products: ", newProducts);
> console.log("Passed product: ", action.productId);
> console.log("Should have found: ", newProducts[1]);
> const toggledProduct = newProducts.findIndex(
> (el) => el.id === action.productId
> );
> console.log("Found: ", toggledProduct);
控制台输出:
All products: Array [
Product {
"amount": 0,
"department": "Molkereiprodukte",
"id": "id1",
"product": "Milch 3,5%",
"status": false,
},
Product {
"amount": 0,
"department": "Molkereiprodukte",
"id": "id2",
"product": "Yoghurt",
"status": false,
},
Product {
"amount": 0,
"department": "Ceralien",
"id": "id3",
"product": "Müsli",
"status": false,
},
]
Passed product: Object {
"id": "id2",
}
Should have found: Product {
"amount": 0,
"department": "Molkereiprodukte",
"id": "id2",
"product": "Yoghurt",
"status": false,
}
Found: -1
为什么 find() 方法没有 return 结果???
提前致谢!
你的 action.productId
是 object
不是 string
const toggledProduct = newProducts.findIndex(
(el) => el.id === action.productId.id /** <--here */
);
findIndex
用于查找需要Array.find
获取元素数据的元素的desire index。你得到 -1
的原因是因为 action.productId 是一个对象。您需要比较 action.productId.id
const toggledProduct = newProducts.find(el => el.id === action.productId.id );
恐怕这应该是显而易见的,因为我的事情是基于普通的 Vanille JS。无论如何,出于任何原因我无法解决我的问题。谁能帮帮我?
我在 reducer 中的代码快照:
> case TOGGLE_PRODUCT:
> const newProducts = [...state.allProducts];
> console.log("All products: ", newProducts);
> console.log("Passed product: ", action.productId);
> console.log("Should have found: ", newProducts[1]);
> const toggledProduct = newProducts.findIndex(
> (el) => el.id === action.productId
> );
> console.log("Found: ", toggledProduct);
控制台输出:
All products: Array [
Product {
"amount": 0,
"department": "Molkereiprodukte",
"id": "id1",
"product": "Milch 3,5%",
"status": false,
},
Product {
"amount": 0,
"department": "Molkereiprodukte",
"id": "id2",
"product": "Yoghurt",
"status": false,
},
Product {
"amount": 0,
"department": "Ceralien",
"id": "id3",
"product": "Müsli",
"status": false,
},
]
Passed product: Object {
"id": "id2",
}
Should have found: Product {
"amount": 0,
"department": "Molkereiprodukte",
"id": "id2",
"product": "Yoghurt",
"status": false,
}
Found: -1
为什么 find() 方法没有 return 结果???
提前致谢!
你的 action.productId
是 object
不是 string
const toggledProduct = newProducts.findIndex( (el) => el.id === action.productId.id /** <--here */ );
findIndex
用于查找需要Array.find
获取元素数据的元素的desire index。你得到 -1
的原因是因为 action.productId 是一个对象。您需要比较 action.productId.id
const toggledProduct = newProducts.find(el => el.id === action.productId.id );