簡體   English   中英

javascript 將變量存儲在數組中以啟用按變量值排序

[英]javascript store variables in an array to enable sorting by variable value

我有許多帶有值的變量:

apples_count = 1;
oranges_count = 4;
bananas_count = 2;

我想將它們存儲在一個數組中(例如fruits = [] ),以便我可以按值對它們進行排序,即

[oranges_count, bananas_count, apples_count]

如果我嘗試使用添加變量oranges_count

fruits.push(oranges_count);

然后添加變量值4但不添加變量本身。

如何將變量存儲在數組中,以便按值對它們進行排序?

不要使用單獨的變量,使用對象數組。

 const fruits = [ {type: "apple", count: 1}, {type: "orange", count: 4}, {type: "banana", count: 2} ]; fruits.sort((a, b) => a.count - b.count); console.log(fruits);

您有 3 個具有類似功能的獨立變量。 考慮使用存儲在單個變量中的對象或數組。 然后你可以在數組上使用數組方法來排序和檢索有序計數,例如:

 const counts = { apples: 1, oranges: 4, bananas: 2, }; const sortedEntries = Object.entries(counts).sort((a, b) => a[1] - b[1]); for (const entry of sortedEntries) { console.log(entry); }

有了上述內容,要更改特定計數,只需執行counts.apples = 5

或者,從一開始就使用數組方法:

 const fruits = [ { name: 'apple', count: 1 }, { name: 'orange', count: 4 }, { name: 'banana', count: 2 }, ]; const sortedFruits = fruits.sort((a, b) => a.count - b.count); for (const fruit of sortedFruits) { console.log(fruit); }

要更改上述數組中對象的計數,請.find具有所需name的對象並將其分配給其count屬性:

fruits.find(({ name }) => name === 'apple').count = 10;

或者像上面一樣創建一個對象,將每個水果名稱映射到它的對象。

存儲對象而不是僅存儲值。 例如,您可以使用以下內容:

 var apples = { amount: 1, name: 'apple', type: 'fruit' }; var oranges = { amount: 4, name: 'orange', type: 'fruit' }; var bananas = { amount: 2, name: 'banana', type: 'fruit' }; var collection = [ apples, oranges, bananas ]; var sorted_collection = collection.sort(( first, second ) => first.amount - second.amount ); console.log( sorted_collection );

暫無
暫無

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

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