Перейти к основному содержимому
← ⚡ JavaScript & the browser·Модуль C8 · Урок 2
ЗаданиеDefine deepEqual(a, b) using JSON.stringify. Define assertDeepEqual(actual, expected, msg). Test: assertDeepEqual({a:1,b:2}, {a:1,b:2}, 'objects equal'); assertDeepEqual([1,[2,3]], [1,[2,3]], 'nested arrays'); try assertDeepEqual([1,2], [2,1], 'order') in try/catch and log err.message.

Deep equality for objects and arrays

100 XP8 min
Теория

=== doesn't work on objects

{a:1} === {a:1} is false — === compares references, not contents. For tests, you need value equality.

function deepEqual(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

deepEqual({ a: 1 }, { a: 1 });    // true
deepEqual([1, 2], [1, 2]);         // true
deepEqual([1, 2], [2, 1]);         // false — order matters

The JSON.stringify trick

  • Fast and short.
  • Handles nested objects/arrays.
  • Two limitations: doesn't handle Map/Set/Date well, and undefined values become absent keys.

For 90% of test cases this is enough. node:test's t.assert.deepStrictEqual is more rigorous (handles Map/Set, distinguishes undefined from missing) but the same idea.

🔒

Зарегистрируйся чтобы кодить

Теория открыта всем. Интерактивный редактор, живой превью и проверка открываются с 7-дневным бесплатным trial — нужна карта, отмена в любое время.

Регистрация — бесплатный trial →

Первые 10 уроков в каждом треке — бесплатные. Карта не нужна.

← НазадСледующий урок →

Получай один совет по Python или веб-разработке — каждый день в почте

Коротко, без воды, без спама. Отписаться — в один клик.