30秒学会 JavaScript 片段 · 2023年10月16日

30秒学会 JavaScript 片段 – Check if object is deep frozen

Checks if an object is deeply frozen.

  • Use recursion.
  • Use Object.isFrozen() on the given object.
  • Use Object.keys(), Array.prototype.every() to check that all keys are either deeply frozen objects or non-object values.

代码实现

const isDeepFrozen = obj =>
  Object.isFrozen(obj) &&
  Object.keys(obj).every(
    prop => typeof obj[prop] !== 'object' || isDeepFrozen(obj[prop])
  );

const x = Object.freeze({ a: 1 });
const y = Object.freeze({ b: { c: 2 } });
isDeepFrozen(x); // true
isDeepFrozen(y); // false

翻译自:https://www.30secondsofcode.org/js/s/is-deep-frozen