javascript for...in 语句
for...in 语句用于对数组或者对象的属性进行循环操作。
for ... in 循环中的代码每执行一次,就会对数组的元素或者对象的属性进行一次操作。
语法:
for
(变量in
对象) { 在此执行代码 }
“变量”用来指定变量,指定的变量可以是数组元素,也可以是对象的属性。
实例:
使用 for ... in 循环遍历数组。
<html> <body> <script type="text/javascript"> var x var mycars = new Array() mycars[0] = "Saab" mycars[1] = "Volvo" mycars[2] = "BMW"for (x in mycars) { document.write(mycars[x] + "<br />") }
</script> </body> </html>
JavaScript for...of 语句
for...of
语句创建一个循环来迭代可迭代的对象。在 ES6 中引入的 for...of
循环,以替代 for...in
和 forEach()
,并支持新的迭代协议。for...of
允许你遍历 Arrays(数组), Strings(字符串), Maps(映射), Sets(集合)等可迭代的数据结构等。
语法:
for (variable of iterable) {
statement
}
- variable:每个迭代的属性值被分配给该变量。
- iterable:一个具有可枚举属性并且可以迭代的对象。
实例:
Arrays(数组)
Arrays(数组)就是类列表(list-like)对象。数组原型上有各种方法,允许对其进行操作,比如修改和遍历等操作。下面手在一个数组上进行的 for...of
操作:
// array-example.js
const iterable = [‘mini‘, ‘mani‘, ‘mo‘];
for (const value of iterable) {
console.log(value);
}
// Output:
// mini
// mani
// mo
其结果就是打印出 iterable
数组中的每一个值。
JavaScript for each...in 语句
使用一个变量迭代一个对象的所有属性值,对于每一个属性值,有一个指定的语句块被执行.
语法:
for each (variable in object) {
statement
}
variable
- 用来遍历属性值的变量,前面的
var
关键字是可选的.该变量是函数的局部变量而不是语句块的局部变量.
object
- 该对象的属性值会被遍历.
statement
- 遍历属性值时执行的语句. 如果想要执行多条语句, 请用(
{ ... }
) 将多条语句括住. - 实例:
-
12345678
<span style=
"font-family: 宋体; font-size: 16px"
><code
class
=
" language-js"
><span
class
=
"token keyword"
>
var
sum <span
class
=
"token operator"
>= <span
class
=
"token number"
>0<span
class
=
"token punctuation"
>;
<span
class
=
"token keyword"
>
var
obj <span
class
=
"token operator"
>= <span
class
=
"token punctuation"
>{prop1<span
class
=
"token punctuation"
>: <span
class
=
"token number"
>5<span
class
=
"token punctuation"
>, prop2<span
class
=
"token punctuation"
>: <span
class
=
"token number"
>13<span
class
=
"token punctuation"
>, prop3<span
class
=
"token punctuation"
>: <span
class
=
"token number"
>8<span
class
=
"token punctuation"
>}<span
class
=
"token punctuation"
>;
<span
class
=
"token keyword"
>
for
each <span
class
=
"token punctuation"
>(<span
class
=
"token keyword"
>
var
item <span
class
=
"token keyword"
>
in
obj<span
class
=
"token punctuation"
>) <span
class
=
"token punctuation"
>{
sum <span
class
=
"token operator"
>+<span
class
=
"token operator"
>= item<span
class
=
"token punctuation"
>;
<span
class
=
"token punctuation"
>}
<span
class
=
"token function"
>print<span
class
=
"token punctuation"
>(sum<span
class
=
"token punctuation"
>)<span
class
=
"token punctuation"
>; <span
class
=
"token comment"
>
// 输出"26",也就是5+13+8的值</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></span>