Циклы

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y = 5, the table below explains the arithmetic operators:

Operator Description Example Result in y Result in x Try it
+ Addition x = y + 2 y = 5 x = 7 Try it »
Subtraction x = y — 2 y = 5 x = 3 Try it »
* Multiplication x = y * 2 y = 5 x = 10 Try it »
Division x = y / 2 y = 5 x = 2.5 Try it »
% Modulus (division remainder) x = y % 2 y = 5 x = 1 Try it »
++ Increment x = ++y y = 6 x = 6 Try it »
x = y++ y = 6 x = 5 Try it »
Decrement x = —y y = 4 x = 4 Try it »
x = y— y = 4 x = 5 Try it »

For a tutorial about arithmetic operators, read our
JavaScript Arithmetic Tutorial.

The in Operator

The in operator returns true if the specified property is in the specified object,
otherwise false:

Example

// Arraysvar cars = ;»Saab» in cars          // Returns false (specify the index number instead of value)0 in cars               // Returns true1 in cars               // Returns true4 in cars               // Returns false (does not exist)»length» in cars        // Returns true  (length is an Array property)// Objects
var person = {firstName:»John», lastName:»Doe», age:50};»firstName» in person   // Returns true»age» in person         // Returns true// Predefined objects»PI» in Math            // Returns true»NaN» in Number         // Returns true»length» in String      // Returns true

Использование for без блоков

Все три выражения в заголовке цикла for являются необязательными.

Например, в блоке инициализации не требуется инициализировать переменные. Цикл в примере ниже полностью идентичен приведённому выше:

Выполнить код »
Скрыть результаты

Как и блок инициализации, блок выражения также не является обязательным. Если вы опускаете выражение, то вы должны обязательно разбить цикл в теле, чтобы не создавать бесконечный цикл:

Выполнить код »
Скрыть результаты

Можно опустить все три блока. Для избежания зацикливания используйте break для завершения цикла, а также изменяйте (увеличивайте или уменьшайте) переменную-счётчик, так чтобы условие для оператора break в какой-то момент сработало:

Выполнить код »
Скрыть результаты

Примечание: Любое из выражений в цикле for может отсутствовать, однако сами точки с запятой обязательно должны присутствовать, иначе будет синтаксическая ошибка.

Definition and Usage

The for statement creates a loop that is executed as long as a condition is
true.

The loop will continue to run as long as the condition is true. It will only
stop when the condition becomes false.

JavaScript supports different kinds of loops:

  • for — loops through a block of code a number of times
  • for/in — loops through the properties of an object
  • for/of — loops through the values of an iterable object
  • while — loops through a block of code while a specified condition is true
  • do/while — loops through a block of code once, and then repeats the loop while a specified condition is true

Tip: Use the break statement
to break out of a loop, and the continue
statement to skip a value in the loop.

Вложенные циклы

Цикл внутри другого цикла называется вложенным. Вложенность циклов формально не ограничивается, однако нужно быть предельно осторожным, чтобы не допустить зацикливания. При каждой итерации внешнего цикла вложенный цикл выполняется полностью. Вложенные циклы можно создавать с помощью инструкции и инструкции .

Пример вложенного цикла:

Выполнить код »
Скрыть результаты

Теперь попытаемся разобраться, как это работает. Первый (внешний) цикл после каждой итерации увеличивает значение переменной i, а второй (внутренний) – переменной j. За одну итерацию внешнего цикла внутренний выполняется девять раз. По условию (i внешний цикл выполнится 9 раз. Соответственно вложенный цикл будет выполнятся тоже 9 раз, а код внутри него – 9*9 итого 81 раз.

Иными словами, код читаем так: натыкаемся на внешний цикл, делаем первый проход, во время прохода натыкаемся на еще один цикл (внутренний), делаем девять проходов по нему, каждый раз выводя текущее значение переменной j. Выводим значение i и далее возвращаемся в начало внешнего цикла для второго прохода и так 9 раз.

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Цикл for

Синтаксис цикла :

В цикле располагаются три выражения, разделяемые точкой с запятой. Эти три выражения имеют следующий порядок выполнения:

  1. Первое выражение всегда вычисляется только один раз – перед первой итерацией. Поэтому обычно в качестве первого выражения выступает определение переменной, которая используется в условии выполнения цикла в качестве счётчика.
  2. Второе выражение определяет условие выполнения цикла. Оно вычисляется перед каждой итерацией и определяет, будет ли выполняться тело цикла. Если результатом вычисления выражения является истинное значение, программный код в теле цикла выполняется. Если возвращается ложное значение, выполнение цикла завершается и управление переходит к следующей после цикла инструкции. Если при первой проверке условия, оно оказывается ложным, код в теле цикла не выполнится ни разу.
  3. После каждой итерации вычисляется третье выражение. Обычно его используют для изменения значения переменной, которая используется в проверке условия выполнения цикла.

Пример цикла :

for (var count = 0; count < 5; count++)
  document.write(count + " ");

Попробовать »

Как видно из примера, цикл в отличие от других циклов позволяет сгруппировать связанный с циклом код в одном месте.

Любое из выражений в цикле может отсутствовать, однако сами точки с запятой обязательно должны присутствовать, иначе будет синтаксическая ошибка. При отсутствии второго выражения цикл будет выполняться бесконечно.

var i = 0;
for (; i < 4; i++) ...

var i = 0;
for (; i < 4; ) ...

for (var i = 1; /* нет условия */ ; i++) ...

// Это эквивалентно следующему коду
for (var i = 1; true; i++) ...

Вместо одного выражения можно указать несколько выражений, разделяя их оператором запятая.

// не выполнится, так как в проверке условия последнее выражение false
for (i = 1; i < 4, false; i++) ...

for (var i = 1, j = 5; i <= 5; i++, j--)
  document.write(i + " " + j +"<br>");

Попробовать »

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Пустые элементы

Массивы JavaScript допускают пустые элементы. Массив ниже синтаксически верный и имеет длину 3 элемента:

const arr = ;

arr.length; // 3

Что еще более запутывает, так это то, что циклические конструкции трактуют иначе, чем . Ниже показано, как четыре циклических конструкции обрабатывают с пустым элементом. for/in и for/each пропускают пустой элемент, for и for/of — нет.

// Prints "a, undefined, c"
for (let i = 0; i < arr.length; ++i) {
  console.log(arr);
}

// Prints "a, c"
arr.forEach(v => console.log(v));

// Prints "a, c"
for (let i in arr) {
  console.log(arr);
}

// Prints "a, undefined, c"
for (const v of arr) {
  console.log(v);
}

Если вам интересно, все 4 конструкции выведут «a, undefined, c» для .

Есть еще один способ добавить пустой элемент в массив:

// Equivalent to ``
const arr = ;
arr = 'e';

forEach() и for/in пропускают пустые элементы в массиве, for и for/of — нет. Поведение forEach() может вызвать проблемы, однако можно заметить, что дыры в массивах JavaScript, как правило, встречаются редко, поскольку они не поддерживаются в JSON:

$ node
> JSON.parse('{"arr":}')
{ arr:  }
> JSON.parse('{"arr":}')
{ arr:  }
> JSON.parse('{"arr":}')
SyntaxError: Unexpected token , in JSON at position 12

Таким образом, вам не нужно особо беспокоиться о дырах в пользовательских данных, если вы не предоставите своим пользователям доступ ко всей среде выполнения JavaScript.

Вывод: for/in и forEach() не реагируют на пустые элементы, также известные как «дыры», в массиве. Редко есть какая-либо причина рассматривать дыры как особый случай, а не рассматривать индекс как значение undefined. Если вы допускаете наличие дыр, ниже приведен пример файла .eslintrc.yml, который запрещает вызов forEach().

parserOptions:
  ecmaVersion: 2018
rules:
  no-restricted-syntax:
    - error
    - selector: CallExpression
      message: Do not use `forEach()`, use `for/of` instead

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.

Given that x = 5, the table below explains the comparison operators:

Operator Description Comparing Returns Try it
== equal to x == 8 false Try it »
x == 5 true Try it »
=== equal value and equal type x === «5» false Try it »
x === 5 true Try it »
!= not equal x != 8 true Try it »
!== not equal value or not equal type x !== «5» true Try it »
x !== 5 false Try it »
> greater than x > 8 false Try it »
< less than x < 8 true Try it »
>= greater than or equal to x >= 8 false Try it »
<= less than or equal to x <= 8 true Try it »

For a tutorial about comparison operators, read our
JavaScript
Comparisons Tutorial.

More Examples

Example

Loop through the indices of an array to collect the car names from the cars
array:

var cars = ;var text = «»;var i;for (i = 0; i < cars.length; i++) {  text += cars + «<br>»;
}

Example above explained:

  • First, we set a variable before the loop starts (var i = 0;)
  • Then, we define the condition for the loop to run. As long as the variable is less than the length of the array (which is 4), the loop will continue
  • Each time the loop executes, the variable is incremented by one (i++)
  • Once the variable is no longer less than 4 (array’s length), the condition is false, and the loop will end

Example

Initiate multiple values in the first parameter:

var cars = ;var i;for (i = 0, len = cars.length, text = «»; i < len; i++) {   text += cars + «<br>»;
}

Example

Omit the first parameter (set values before the loop starts):

var cars = ;var i = 2;var len = cars.length;var text = «»;for (; i < len; i++) {
  text += cars + «<br>»;
}

Example

Using the continue statement — Loop through a block of code, but skip the value of «3»:

var text = «»;var i;for (i = 0; i < 5; i++) {  if (i == 3) {    continue;
  }  text += «The number is » + i + «<br>»;}

Example

Using the break statement — Loop through a block of code, but exit the loop when the variable i is equal
to «3»:

var text = «»;var i;for (i = 0; i < 5; i++) {  if (i == 3) {
    break;  }  text += «The number is » + i + «<br>»;}

Example

Omit the second parameter. In this example, we also use the break statement to exit the loop when i is equal to «3» (if the second parameter is omitted, you must provide a break
inside the loop. Otherwise the loop will never end, and your browser will crash):

var cars = ;var text = «»;
var i;for (i = 0; ; i++) {  if (i == 3) {    break;
  }  text += cars + «<br>»;}

Example

Loop through the indices of an array, in descending order (negative
increment):

var cars = ;var text = «»;var i;
for (i = cars.length — 1; i >= 0; i—) {  text += cars + «<br>»;
}

Example

Omit the last parameter, and increment the values inside the loop:

var cars = ;var i = 0;var len = cars.length;for (; i < len;) {   text += cars + «<br>»;
 
i++;}

Example

Loop through the nodes of a NodeList object and change the background color of all <p> elements in the list:

var myNodelist = document.getElementsByTagName(«P»);var i;for (i = 0; i < myNodelist.length; i++) {  myNodelist.style.backgroundColor = «red»;}

Example

An example of a nested loop (a loop inside a loop):

var text = «»;var i, j;for (i = 0; i < 3; i++) {  text += «<br>» + «i = » + i + «, j = «;
  for (j = 10; j < 15; j++) {    document.getElementById(«demo»).innerHTML = text += j + » «;
  }}

Цикл while

Инструкция while (англ. до тех пор, пока) создает цикл с предусловием. В скобках после слова while указывают некоторое логическое выражение или значение. Цикл начнется если значение этого выражения равно и будет работать до тех пор, пока это условие не обратится в . Общий синтаксис этого цикла выглядит так:

Следующий цикл while исполняется, пока значение переменной i меньше 3:

Выполнить код »
Скрыть результаты

После окончания третьей итерации условие i больше не является истинным, поэтому цикл завершается.

Для создания бесконечного цикла в качестве условия достаточно задать булево значение :

Это общепринятый способ создания бесконечного цикла. В прочих случаях (к примеру, если в рассмотренном нами примере убрать в коде i++) возможен вариант (в теории) создания бесконечного цикла. На практике, браузер выведет сообщение о «зависшем» скрипте и посетитель его остановит.

Операторы break и continue

Циклом можно управлять с помощью операторов break и continue.

Оператор break приводит к выходу из цикла или инструкции и передает управление
операторам, следующим за ними.

В следующем примере создаётся счётчик, значения которого должны изменяться от до , однако оператор break прерывает цикл после итераций:

Выполнить код »
Скрыть результаты

Для вложенных циклов оператор используется с меткой, с помощью которой завершается работа «меченой» инструкции. Метка позволяет выйти из любого блока кода. Метка имеет вид , имя должно быть уникальным. Она ставится перед циклом или блоком инструкций, которые нужно завершить с помощью :

Выполнить код »
Скрыть результаты

Указание имени метки (без двоеточия) за ключевым словом приводит к выходу из цикла или инструкции. Между ключевым словом и именем метки не допускается перевод строки. Вызов завершит вложенный цикл, а ищет ближайший внешний цикл с такой меткой и переходит в его конец.

Оператор continue прерывает текущее выполнение цикла и переходит к выполнению следующего шага этого цикла. При этом, цикл возвращается непосредственно к своему условию, а цикл сначала вычисляет выражение инкремента, а затем возвращается к условию.

Рассмотрим пример:

Выполнить код »
Скрыть результаты

В теле цикла инструкция с помощью оператора проверяет, является ли число четным. Если да, итерация цикла завершается до увеличения переменной , но цикл продолжается со следующей итерации со значением , увеличенным на единицу. Затем цикл выполняется до естественного завершения при значении , равном 10. Переменная подсчитывает количество итераций цикла. Окончательное значение равно 5, а не 9, потому что четные операции инкремента пропускаются из-за оператора .

Оператор , как и , можно использовать вместе с «помеченными» инструкциями для
возврата к конкретному месту в коде. Чаще всего это делается во вложенных циклах, например:

Выполнить код »
Скрыть результаты

В этом примере для внешнего цикла добавлена метка outer_mask. Каждый цикл включает 5 итераций, то есть инструкция предположительно должна быть выполнена 25 раз, после чего переменная должна быть равна 25. Оператор завершает выполнение внутреннего цикла, начиная новую итерацию внешнего. Она выполняется, когда равно 3, то есть пропускаются две итерации внутреннего цикла, из-за чего в итоге имеет значение 23.

Заключение

Как правило, for/of — это самый надежный способ перебора массива в JavaScript. Он более лаконичен, чем обычный цикл for, и не имеет такого количества граничных случаев, как for/in и forEach(). Основным недостатком for/of является то, что вам нужно проделать дополнительную работу для доступа к индексу массива (см. дополнение), и вы не можете строить цепочки кода, как вы можете это делать с помощью forEach(). Но если вы знаете все особенности forEach(), то во многих случаях его использование делает код более лаконичным.

Дополнение: Чтобы получить доступ к текущему индексу массива в цикле for/of, вы можете использовать функцию  .

for (const  of arr.entries()) {
  console.log(i, v); // Prints "0 a", "1 b", "2 c"
}

Оригинал: For vs forEach() vs for/in vs for/of in JavaScript

Spread the love

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector