我有一個關于陣列的問題。我是 javascript 新手,我正在撰寫一個程式,該程式具有按類別過濾陣列的 20 個元素的功能。也就是說,我有 3 個按鈕,通過單擊其中一個按鈕,該功能被打開并開始顯示過濾后的元素。請告訴我如何做到這一點?我已經嘗試了很多方法,但最終什么也沒發生,雖然我認為我在某個地方犯了錯誤。
大批:
window.products = [
{
id: "i8",
title: "Iphone 8",
description:
"The iPhone 8 ",
price: 19900,
discontinued: false,
categories: ["c1"]
},
{
id: "i10",
title: "Iphone X",
description: "Iphone 10",
price: 39900,
discontinued: false,
categories: ["c1"]
},
{
id: "i11",
title: "Iphone 11",
description: "The iPhone 11 ",
price: 69900,
discontinued: false,
categories: ["c1"]
};
我的功能
function myFunction() {
document.getElementById("selected-category").innerHTML = "Iphones";
document.getElementById("category-products").innerHTML = "";
for (i = 0; i < 20; i ) {
document.getElementById("category-products").innerHTML = window.id;
const found = window.products.find(window.products.categories == "c1");
console.log(found);
}
}
部分帶有按鈕的 html 代碼
<button onclick="myFunction()">Iphones</button>
uj5u.com熱心網友回復:
首先,您的windows.products = [ ... };. 它沒有正確關閉(您需要]在};.
然后,該find方法需要傳遞一個處理陣列元素的函式。
您嘗試window.products.categories == "c1"的結果為 false,因為該屬性在陣列categories中不存在。window.products你undefined在左邊,在右邊有一個字串,所以它總是false。你會得到“false 不是函式”。
將 find() 與函式一起使用的示例:
const found = window.products.find( element => element.categories == "c1" );
或
const found = window.products.find( function(element) {
return element.categories == "c1"
});
但是之后:
- 以上
== "c1"不是您應該使用的,因為它僅由于從陣列到字串的型別強制而匹配,并且僅在類別只有“c1”且沒有其他元素時匹配。你應該使用includes方法。 - “查找”只會給您一個匹配的產品。使用“過濾器”查找所有匹配的。
如果你只需要搜索一個鍵“c1”,你可以使用const found = window.products.filter( product=> product.categories.includes("c1"));and for兩個鍵“c1”和“c2”:const found = window.products.filter( product => product.categories.includes("c1") && product.categories.includes("c2"));
但我認為你不應該使用上面的,因為你應該處理用戶搜索的情況對于多個鍵。
const searchList = ['c1', 'c2', 'c3']
const found = window.products.filter ( function( product) {
//returns true if element.categories contains all of 'c1', 'c2' and 'c3'
return searchList.every( searchKey => product.categories.includes(searchKey)) ;
})
您也可以在一行中進行搜索,但可能更難閱讀:
const searchList = ['c1', 'c2', 'c3']
const found = window.products.filter ( product => searchList.every( searchKey => product.categories.includes(searchKey)) );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450668.html
標籤:javascript html 数组 排序 筛选
