2017-06-23 35 views
2

我期待存儲唯一字符串(因此設置)的列表並希望根據索引檢索值。我用得到(索引號)但事實證明它返回undefined。所以看起來我不明白Set很好。如何從設置獲取基於索引的值

如果需要檢索的值,我們必須將其轉換回數組,然後只讀取它或使用「get(index)」它可以實現嗎?

另外,我已檢查Set tests瞭解得到(索引)但仍不清楚。

const { Set } = require('immutable'); 

const set = Set(["ab", "cd", "ef"]) 
console.log(set.get(1)) //logs undefined 
console.log(set.toJS()[1]) //logs "cd" 
+1

第一如果你正在使用ES6'Set',或Immutable.js'Set',你需要自己澄清 - 它們是不同的。首先,前者沒有'get'。 Immutable.js爲所有集合提供'get',但是使用集合它只返回項目本身:'new Immutable.Set()。add(「foo」)。get(「foo」)'returns'「foo」' (和'new Immutable.Set()。add(「foo」)。get(「bar」)'returns'undefined')。集合本質上是無序的,「集合索引」是沒有意義的。如果你想索引,你想要一個數組(或至少'Immutable.IndexedSeq')。 – Amadan

+0

@Amadan感謝您的輸入,Set的Item不是嚴格的命令讓我使用List(),它看起來很有前途。看來我只是抓了Immutable的表面:) –

回答

1

在這裏,我想在ES2015使用設置的情況下直接ImmutableJS

你可以編寫自定義的功能是這樣的:

Set.prototype.getByIndex = function(index) { return [...this][index]; } 
 

 
var set = new Set(['a', 'b', 'c']) 
 

 
console.log(set.getByIndex(0)) // 'a'

注意,展開式運算符將一個集合轉換爲一個數組,以便您可以使用索引訪問元素

0

使用一成不變的獲得方式是通過「鑰匙」不是指數

console.log(set.get("cd")) // logs cd, at index 1 

,如果你想從集合的迭代器獲取元素,你必須擴展不可改變的集

Set.prototype.getByIdx = function(idx){ 
    if(typeof idx !== 'number') throw new TypeError(`Argument idx must be a Number. Got [${idx}]`); 

    let i = 0; 
    for(let iter = this.keys(), curs = iter.next(); !curs.done; curs = iter.next(), i++) 
    if(idx === i) return curs.value; 

    throw new RangeError(`Index [${idx}] is out of range [0-${i-1}]`); 
} 

const set = Set(["ab", "cd", "ef"]); 

console.log(set.getByIdx(1)) //logs cd 
相關問題