首頁 > web前端 > js教程 > 主體

王林
發布: 2024-08-26 21:42:32
原創
273 人瀏覽過

套

  • 在 ES6 之前,JS 只有兩種內建資料結構,即陣列和物件。 ES6 引進了兩個新的 DS:套、Map。
  • 用於儲存和有序檢索使用陣列。
  • 僅當順序不重要時才使用集合,而且您只需要檢查資料結構中元素是否存在。
  • 集合並不是為了取代陣列。數組更重要。

- 每當需要依序儲存值以及重複值時,就必須使用陣列。

## Usecase: To remove duplicate values of arrays.
const order = ['pizza','burger','pasta','noodles','pizza','noodles','burger'];

const items = new Set(order);
items; // All duplicate values are removed

const city = new Set("California").size;
city; // 8
登入後複製

套裝:

  • 集合也是像 String 一樣的可迭代物件。
  • 獨特值的集合。
const city = new Set("California");
city;     // Set(8) { 'C', 'a', 'l', 'i', 'f', 'o', 'r', 'n' }

登入後複製
## Difference between Set & Array:
1. Although looks similar to array, but it has no key-value pairs. Hence, set[0] is invalid.
2. Only a list of unique values, all duplicate removed.
3. Order of element is irrelevant

## Similarities between Arrays & 套:
1. Set has size property, Array has length propery.
2. Set has 'has' method, Array has includes method.

const order = ['pizza','burger','pasta','noodles','pizza','noodles','burger'];

const items = new Set(order);
items; // Set(4) { 'pizza', 'burger', 'pasta', 'noodles' }


//Both array and sets are iterables. Hence easier to convert from sets to array.
[...items];
登入後複製

Adv:儘管可以保存混合資料類型,但永遠無法重複。
最常見的可迭代物件是數組。前任。語法:new Set(可迭代)

集合的方法和屬性清單:

.size;  // returns a numerical value
.has('name'); // returns a boolean value
.add('name');  // returns the set with added value
.delete('name'); // returns a boolean value
.clear(); // deletes all elements. returns Set(0) {} 


登入後複製

以上是套的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!