Новые версии JavaScript поддерживают for..of
синтаксис
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
for (const c of colors)
{ if (c.length > 4)
console.log(c, "greater than 4")
else if (c.length < 4)
console.log(c, "less than 4")
else
console.log(c, "equal to 4")
}
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
Вы должны разделить задачи цикла и проверки длины с помощью функции -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = str =>
{ if (str.length > 4)
return "greater than 4"
else if (str.length < 4)
return "less than 4"
else
return "equal to 4"
}
for (const c of colors)
console.log(c, checkLength(c))
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
JavaScript - это мультипарадигмальный язык , поэтому он поддерживает написание одной и той же программы в самых разных стилях -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = str =>
{ if (str.length > 4)
console.log(`${str} is greater than 4`)
else if (str.length < 4)
console.log(`${str} is less than 4`)
else
console.log(`${str} is equal to 4`)
}
colors.forEach(checkLength)
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
Поддержка JavaScript для выражений также довольно хороша, устраняя необходимость в ключевых словах императивного стиля, таких как if
, else
, switch
, for
, while
, do
и даже return
-
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = x =>
x.length > 4 // if ...
? `${x} is greater than 4`
: x.length < 4 // else if ...
? `${x} is less than 4`
: `${x} is equal to 4` // else
console.log(colors.map(checkLength))
// [ "teal is equal to 4"
// , "violet is greater than 4"
// , "silver is greater than 4"
// , "green is greater than 4"
// , "red is less than 4"
// , "purple is greater than 4"
// ]