站长资讯网
最全最丰富的资讯网站

深入了解JS中的for…of循环

本篇文章带大家深入了解一下JavaScript中的for…of循环。有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

深入了解JS中的for...of循环

for…of语句创建的循环可以遍历对象。在ES6中引入的for…of可以替代另外两种循环语句for…in和forEach(),而且这个新的循环语句支持新的迭代协议。for…of允许你遍历可迭代的数据结构,比如数组、字符串、映射、集合等。

语法

for (variable of iterable) {     statement }
  • variable:每个迭代的属性值被分配给variable

  • iterable:一个具有可枚举属性并且可以迭代的对象

我们使用一些示例来阐述。

Arrays

array是简单的列表,看上去像object。数组原型有多种方法,允许在其上执行操作,比如遍历。下面的示例使用for…of来对一个array进行遍历操作:

const iterable = ['mini', 'mani', 'mo'];  for (const value of iterable) {     console.log(value); }  // Output: // => mini // => mani // => mo

其结果就是打印出iterable数组中的每一个值。

Map

Map对象持有key-value对。对象和原始值可以当作一个keyvalueMap对象根据插入的方式遍历元素。换句话说,for...of在每次迭代中返回一个kay-value对的数组。

const iterable = new Map([['one', 1], ['two', 2]]);  for (const [key, value] of iterable) {     console.log(`Key: ${key} and Value: ${value}`); }  // Output: // => Key: one and Value: 1 // => Key: two and Value: 2

Set

Set对象允许你存储任何类型的唯一值,这些值可以是原始值或对象。Set对象只是值的集合。Set元素的迭代是基于插入顺序,每个值只能发生一次。如果你创建一个具有相同元素不止一次的Set,那么它仍然被认为是单个元素。

const iterable = new Set([1, 1, 2, 2, 1]);  for (const value of iterable) {     console.log(value); }  // Output: // => 1 // => 2

尽管我们创建的Set有多个12,但遍历输出的只有12

String

字符串用于以文本形式存储数据。

const iterable = 'javascript';  for (const value of iterable) {     console.log(value); }  // Output: // => "j" // => "a" // => "v" // => "a" // => "s" // => "c" // => "r" // => "i" // => "p" // => "t"

在这里,对字符串执行迭代,并打印出每个索引上(index)的字符。

Arguments Object

把一个参数对象看作是一个类似数组的对象,与传递给函数的参数相对应。这是一个用例:

function args() {     for (const arg of arguments) {         console.log(arg);     } }  args('a', 'b', 'c');  // Output: // => a // => b // => c

你可能在想,到底发生了什么?正如我前面说过的,当调用函数时,参数会接收传入args()函数的任何参数。因此,如果我们将20个参数传递给args()函数,我们将输出20个参数。

在上面的示例基础上做一些调整,比如给args()函数,传入一个对象、数组和函数:

function fn(){ return 'functions'; }  args('a', 'w3cplus', 'c',{'name': 'airen'},['a',1,3],fn());  // Output: // => "a" // => "w3cplus" // => "c" // => Object { // =>     "name": "airen" // => } // => Array [ // =>    "a", // =>    1, // =>    3 // => ] // => "functions"

Generators

生成器是一个函数,它可以退出函数,稍后重新进入函数。

function* generator(){      yield 1;      yield 2;      yield 3;  };  for (const g of generator()) {      console.log(g);  }  // Output: // => 1 // => 2 // => 3

function* 定义一个生成器函数,该函数返回生成器对象。

赞(0)
分享到: 更多 (0)