2017-06-23 34 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 
相关问题