Javascript for/of statement

Цикл for…of

Цикл for…of был добавлен в ES2015, для итерирования итерированных коллекций. То есть объектов что имеют свойство .
Свойство позволяет нам обойти коллекцию вызывая функцию ().next() для получения следующего элемента. Он применим к объектам классов Array, String, Map, Set, Uint8Array…

Пример for…of

let arr=;
const it = arr();
console.log(it.next().value)
console.log(it.next().value)
console.log(it.next().value)

// result
angular
typescript
react
undefined

for (const element of arr) {
    console.log(element);
}
// Result
angular
typescript
react
undefined

Цикл for…of проходит по элементах коллекции и присваивает их значение переменой element.

Также можно использовать ключевые слова break и continue.

for (const element of ) {
    if (x.length === 0) break;
    console.log(element);
}

Подводные камни for-of: он применим только к итерируемым объектам

Значение после of должно быть итерируемым. Что означает что нужно вручную переформатировать объект в массив чтобы получить его свойства.

const user = { email:'some@mail.com',login:'root' };

for (const prop of user) { // TypeError
    console.log(prop);
}

for (const prop of Array.from(user)) { // OK
    console.log(prop);
}

Итерирование с использованием деструкции

Использование for…of вместе с destructuring assingment особенно полезно для итерирования пар .

const someMap = new Map();
someMap.set('key1', 10).set('key2', 20);
for (const  of someMap) {
  console.log(`key = ${key}, value = ${value}`);
}
// Result:
key = key1, value = 10
key = key2, value = 20

Array.prototype.entries() также возвращает итерируемые пары ключ значения

const array = ;
for (const  of arr.entries()) {
    console.log(`key = ${key}, value = ${value}`);
}
// Result:
key = 0, value = angular
key = 1, value = typescript
key = 2, value = react

Просмотры:
2 771

 

Definition and Usage

The for/in statement loops through the properties of an object.

The block of code inside the loop will be executed once for each property.

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

Note: Do not use the for/in statement to loop through arrays
where index order is important. Use the for statement instead.

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

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.

Цикл 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 Bitwise Operators

Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.

Operator Description Example Same as Result Decimal
& AND x = 5 & 1 0101 & 0001 0001  1
| OR x = 5 | 1 0101 | 0001 0101  5
~ NOT x = ~ 5  ~0101 1010  10
^ XOR x = 5 ^ 1 0101 ^ 0001 0100  4
<< Left shift x = 5 << 1 0101 << 1 1010  10
>> Right shift x = 5 >> 1 0101 >> 1 0010   2

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010

Parameter Values

Parameter Description
statement1 Optional. Executed before the loop (the code block) starts. Normally this statement is used to initialize a counter variable. To initiate multiple values, separate each value with a comma.
Note: This parameter can be omitted. However, do not omit the semicolon «;»
statement2 Optional. Defines the condition for running the loop (the code block). Normally this statement is used to evaluate the condition of the counter variable. If it returns true, the loop will start over again, if it returns false, the loop will end.Note: This parameter can be omitted. However, do not omit the semicolon «;». Also, if you omit this parameter, you must provide a break inside the loop. Otherwise the loop will never end, which will crash your browser
statement3 Optional. Executed each time after the loop (the code block) has been executed. Normally this statement is used to increment or decrement the counter variable.Note: This parameter can be omitted (e.g. to increase/decrease values inside the loop)

Различные типы циклов в PHP

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

  1. while — перебирает блок кода, пока условие не станет истинным.
  2. do … while — блок кода выполняется один раз, а затем условие проверяется. Если условие истинно, выражение повторяется до тех пор, пока указанное условие истинно.
  3. for — перебирает блок кода, пока счетчик не достигнет указанного числа.
  4. foreach — проходит через блок кода для каждого элемента в массиве.

Цикл while в PHP

Оператор while будет циклически проходить по блоку кода, пока условие в операторе while будет равным true.

while(условие){
  // Код который нужно выполнять
}

Пример ниже создает цикл, который начинается с $i = 1. Цикл будет продолжать выполняться до тех пор, пока $i меньше или равен 3. Значение $i будет увеличиваться на 1 при каждом запуске цикла:

<?php
$i = 1;
while($i <= 3){
  $i++;
  echo "Number " . $i . "<br>";
}
?>

Цикл do … while в PHP

Цикл do-while является вариантом цикла while, который оценивает условие в конце каждой итерации цикла. В цикле do-while блок кода выполняется минимум один раз, а затем условие оценивается, если условие истинно, цикл повторяется до тех пор, пока указанное условие истинно.

do{
  // Код который выполнится как минимум 1 раз
}
while(условие);

В следующем примере определяется цикл, который начинается с $i = 1. Затем он увеличит $i на 1 и отобразит вывод. Затем условие оценивается и цикл продолжает выполняться, пока $i меньше или равно 3.

<?php
$i = 1;
do {
  $i++;
  echo "Number " . $i . "<br>";
}
while($i <= 3);
?>

Разница циклов while и do … while

Цикл while отличается от цикла do-while одним важным моментом — с циклом while проверяемое условие проверяется в начале каждой итерации цикла, поэтому, если условное выражение имеет значение false, цикл никогда не будет выполнен.

С другой стороны, в цикле do-while цикл всегда будет выполняться один раз, даже если условное выражение ложно, поскольку условие оценивается в конце итерации цикла, а не в начале.

Циклы for в PHP

Цикл for повторяет блок кода, пока не будет выполнено определенное условие. Обычно он используется для выполнения блока кода определенное количество раз.

for(инициализация; условие; инкремент){
  // Код который нужно выполнить
}

Параметры цикла for имеют следующие значения:

  • инициализация — используется для инициализации переменных счетчика, вычисляется один раз перед первым выполнением тела цикла.
  • условие — в начале каждой итерации условие оценивается. Если оно принимает значение true, цикл продолжается, и вложенные команды выполняются. Если значение равно false, выполнение цикла заканчивается.
  • инкремент — обновляет счетчик цикла новым значением, обычно выполняется в конце каждой итерации.

Пример ниже создает цикл, который начинается с $i = 1. Цикл будет продолжаться до тех пор, пока $i будет меньше или равно 3. Переменная $i будет увеличиваться на 1 при каждом запуске цикла:

<?php
for($i=1; $i<=3; $i++){
  echo "Number " . $i . "<br>";
}
?>

Цикл foreach в PHP

Цикл foreach обычно используется для перебора элементов массива (переводится как «для каждого»).

foreach($array as $value){
  // Код который нужно выполнить
}

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

<?php
$colors = array("Red", "Green", "Blue");

// Проходим по всем элементам массива
foreach($colors as $value){
  echo $value . "<br>";
}
?>

Существует еще один синтаксис цикла foreach, который является дополнением первого.

foreach($array as $key => $value){
  // Код который нужно выполнить
}

Этот цикл используется для работы с ассоциативными массивами.

<?php
$superhero = array(
  "name" => "Vasya Pupkin",
  "email" => "vasyapupkin@mail.com",
  "age" => 18
);

// Проходим по массиву
foreach($superhero as $key => $value){
  echo $key . " : " . $value . "<br>";
}
?>

В результате вы увидите это:

name : Vasya Pupkin
email : vasyapupkin@mail.com
age : 18

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

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()

The typeof Operator

The typeof operator returns the type of a variable, object, function or
expression:

Example

typeof «John»                
// Returns string
typeof 3.14                  
// Returns number
typeof NaN                   
// Returns number
typeof false                 
// Returns boolean
typeof            // Returns object
typeof {name:’John’, age:34} 
// Returns objecttypeof new Date()            
// Returns objecttypeof function () {}         // Returns function
typeof myCar                 
// Returns undefined (if myCar is not declared)
typeof null                  
// Returns object

Please observe:

  • The data type of NaN is number
  • The data type of an array is object
  • The data type of a date is object
  • The data type of null is object
  • The data type of an undefined variable is undefined

You cannot use typeof to define if a JavaScript object is an
array (or a date).

Перебор коллекций — Цикл foreach C#

Допустим, мы имеем массив значений, не важно каких: числа, строки, символы… Для перебора массива удобно использовать этот вид цикла. Выглядит он следующим образом:. Предположим, у нас есть список городов, и нужно найти все города, начинающиеся с заданного символа

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

Пользователь вводит символ, после чего для каждого элемента массива проверяется, начинается ли он с заданного символа. И, если условие выполняется, элемент массива запоминается в результирующей строке. Главным плюсом foreach является то, что он исключает возможность выхода за границы массива.

Управление циклом. Команды break и countinue

Для управления циклом в языке C# используются два оператора: break и continue.

Оператор break используется для прерывания выполнения цикла. Пусть, нам нужно найти некоторый элемент в массиве. Так, используя цикл, мы можем выйти из цикла, как только найдем искомый элемент.

Так мы находим индекс искомого слова в массиве, при этом не выполняем лишних операций после того, как найдем искомый элемент.

Оператор continue используется для перехода к следующей итерации цикла. Рассмотрим задачу: необходимо вычислить сумму пяти частных вида:

Как вы видите, при i = a будет получена ошибка «Деление на ноль». В данном случае мы можем пропускать значение счетчика, которое приводит к ошибке.

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-in

Цикл используется для перебора в случайном порядке перечисляемых свойств объекта и имеет следующий синтаксис:

for (переменная in объект)
  инструкция;

Слева от ключевого слова указывается имя переменной, которой перед началом каждой итерации цикла присваивается в виде строки имя одного из свойств объекта. Справа от ключевого слова указывается объект, свойства которого будут перебираться циклом. Цикл будет выполняться до тех пор, пока не будут перебраны все доступные свойства. Если переменная, представляющая объект, будет иметь значение или цикл не выполнится ни разу:

var obj = {x: 5, y: 10};

for (var prop in obj) {
  alert(prop);
}

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

С этой темой смотрят:

  • Инструкции break и continue
  • Метки инструкций
  • Выражения и инструкции
  • Преобразование типов данных
Добавить комментарий

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

Adblock
detector