Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The MDN documentation for Set says that JavaScript Set objects retain insertion order of elements:

(SetMDN文档说JavaScript Set对象保留元素的插入顺序:)

Set objects are collections of values, you can iterate its elements in insertion order.

(集合对象是值的集合,可以按插入顺序对其元素进行迭代。)

Is there a way to get the last item inserted into a Set object?

(有没有一种方法可以将最后一个项目插入Set对象中?)

var s = new Set();
s.add("Alpha");
s.add("Zeta");
s.add("Beta");

console.log(getLastItem(s)); // prints "Beta"

Edit

(编辑)

It is possible to implement a Linked Set datastructure container class that has the same interface as Set and has the desired capability.

(它可以实现具有相同的接口,一组链接数据结构容器类Set并具有所需的能力。)

See my answer below.

(请参阅下面的答案。)

  ask by Tamas Hegedus translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
292 views
Welcome To Ask or Share your Answers For Others

1 Answer

I was not able to find any method to get last value inserted in set from ECMA 2015 Specification , may be they never intended such a method, but you can do something like:

(我找不到任何方法可以从ECMA 2015规范中获取插入集合中的最后一个值,可能是他们从未打算使用这种方法,但是您可以执行以下操作:)

const a = new Set([1, 2, 3]);
a.add(10);
const lastValue = Array.from(a).pop();

Edit:

(编辑:)

on second thought, a space efficient solution might be:

(再考虑一下,一个节省空间的解决方案可能是:)

function getLastValue(set){
  let value;
  for(value of set);
  return value;
}

const a = new Set([1, 2, 3]);
a.add(10);
console.log('last value: ', getLastValue(a));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...