簡體   English   中英

具有定義鍵和多維的數組

[英]Array with defined key and multidimensional

我在沒有幫助的情況下查看了其他類似的帖子,它們都從一個已經創建的多維數組開始,我想使用 .push 方法創建一個

我的數組是:

ItemsArray.push({ 
    BMW:{Model:X5,Model:X6,Model:X3 },
    Range Rover:{Model:Sports,Model:Venar}
});

汽車品牌由按鈕定義,因此如果用戶單擊 Fiat,則列表會生成諸如{Model: Punto}並使用Fiat:{Model: Punto}推送到上述數組中。

我嘗試使用: ItemsArray[CarName].Models.push但它給出了錯誤

ItemsArray[CarName].Item' 未定義

您提供的部分代碼將永遠無法工作。 例如: BMW:{Model:X5,Model:X6,Model:X3 } 它構造了一個對象,並且您要添加相同的屬性Model三次。 結果是這個對象: { Model: X3 } 您必須為此使用數組而不是對象,就像我在下面的示例中所做的那樣。

除此之外,使用數組來存儲所有數據是不切實際的。 你會得到這樣的數據結構:

 [ { brand: 'BMW', models: [ name: 'X5' ] }, { brand: 'Fiat', models: [ name: '500' ] }, ]

現在,每當您想要向品牌添加模型時,您首先必須在數組中查找品牌屬性與您想要添加模型的品牌相匹配的條目。 只有在這樣做之后,您才能開始為品牌操縱模型。

我認為您想要做的是擁有一個具有每個品牌屬性的對象。 在此屬性下,您可以存儲包含該品牌模型的數組。 我在下面的代碼片段中模擬了一些東西。

 const // This object will get an property per brand. modelsPerBrand = {}, // An array with the brand we support. brands = ['BMW', 'Ford', 'Fiat']; /** * This method will add a single model to a single brand. */ function addModelToBrand(brand, model) { const vehicles = modelsPerBrand[brand]; if (vehicles === undefined) { // Log a message or alternatively add the new brand to the modelsPerBrand object. console.log(`Unknown brand "${ brand }"`); return; } // Add the provided model to the array of models for the brand. vehicles.push({ name: model }); } /** * This method makes it easy to add multiple models at once to a * single car brand. */ function addModelsToBrand(brand, models) { if (modelsPerBrand[brand] === undefined) { console.log(`Unknown brand "${ brand }"`); return; } models.forEach(model => addModelToBrand(brand, model)); } // Create an empty array for each brand. It will result in an object // like this: // { // BMW: [], // Ford: [], // Fiat: [] // } brands.forEach(brand => modelsPerBrand[brand] = []); console.log('Object with brands: ', modelsPerBrand); // Add a single model to a brand. The object we have will now look // like this: // { // BMW: [ { name: 'X5' } ], // Ford: [], // Fiat: [] // } addModelToBrand('BMW', 'X5'); console.log('Object after adding BMW X5: ', modelsPerBrand); // Add a multiple models to a brand addModelsToBrand('Fiat', ['500', '500L']); console.log('Object after adding Fiat 500 and 500L: ', modelsPerBrand); // Add model to non-existing brand addModelsToBrand('KIA', 'Stinger'); // List all models for a brand: modelsPerBrand.Fiat.forEach(model => console.log(`Fiat ${ model.name }`));

或者,您可以使用Map而不是vehiclesPerBrand變量的對象,但我不確定您打算如何使用它。 這就是為什么我使用Object代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM