Prejsť na hlavný obsah
← ⚡ JavaScript & the browser·Modul C5 · Lekcia 3
ÚlohaWrite sumOrEcho(x): if x is an array, return sum of all elements; else return x unchanged. Log sumOrEcho([1,2,3]), sumOrEcho("hi"), sumOrEcho(42), sumOrEcho([]).

Array.isArray — when typeof lies

100 XP7 min
Teória

typeof can't see arrays

typeof [] is "object". Same as typeof null, typeof {}, typeof new Date(). Useless for telling arrays apart from plain objects.

typeof [];           // "object"
typeof { a: 1 };     // "object"
typeof null;         // "object"

Array.isArray([]);        // true
Array.isArray({ a: 1 });  // false
Array.isArray(null);      // false

sumOrEcho

A real shape you'll write:

function sumOrEcho(x) {
  if (Array.isArray(x)) {
    return x.reduce((s, n) => s + n, 0);
  }
  return x;
}

sumOrEcho([1, 2, 3]);  // 6
sumOrEcho("hi");       // "hi"
sumOrEcho(42);         // 42

Why not instanceof Array?

instanceof Array fails for arrays from a different window (iframes, web workers — they get their own Array constructor). Array.isArray is the safe answer.

🔒

Zaregistruj sa a začni programovať

Teória je otvorená pre každého. Editor, živý náhľad a kontrola sa odomknú so 7-dňovou bezplatnou skúškou — karta potrebná, zruš kedykoľvek.

Registrácia — bezplatná skúška →

Prvých 10 lekcií v každej trase je zdarma. Karta nie je potrebná.

← PredchádzajúcaĎalšia lekcia →

Jeden tip k Pythonu alebo webu denne — e-mailom

Krátke, ručne písané, žiadny spam. Odhlásiť jedným klikom.