30秒学会 JavaScript 片段 · 2022年4月21日

30秒学会 JavaScript 片段 – Freeze Set object

Creates a frozen Set object.

  • Use the Set constructor to create a new Set object from iterable.
  • Set the add, delete and clear methods of the newly created object to undefined, so that they cannot be used, practically freezing the object.

代码实现

const frozenSet = iterable => {
  const s = new Set(iterable);
  s.add = undefined;
  s.delete = undefined;
  s.clear = undefined;
  return s;
};

frozenSet([1, 2, 3, 1, 2]);
// Set { 1, 2, 3, add: undefined, delete: undefined, clear: undefined }

翻译自:https://www.30secondsofcode.org/js/s/freeze-set-object