Javascript magic. Whats going on?

Try:

for (const index in [1,2,3]) console.log(`index ${index} equal 1 ? ${index === 1}`, )

for (const index in [1,2,3]) 
  console.log(`index ${index} equal 1 ? ${index === 1}`, )

Result:

index 0 equal 1 ? false
index 1 equal 1 ? false // << this guy
index 2 equal 1 ? false

Expect:

index 0 equal 1 ? false
index 1 equal 1 ? true // << this guy
index 2 equal 1 ? false

Ответы (2 шт):

Автор решения: Igor

for (const index in [1,2,3]) 
  console.log(`index ${index} ${typeof index} equal 1 ? ${index === 1}`, )

→ Ссылка
Автор решения: vsemozhebuty

Индексы массива являются строками (array indices are strings):

for (const index in [1,2,3]) console.log(`index ${index} equal 1 ? ${index === '1'}`);

Можно использовать нестрогое сравнение (you can use non-strict comparison though):

for (const index in [1,2,3]) console.log(`index ${index} equal 1 ? ${index == 1}`);

→ Ссылка