Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 中的迭代器(iterators)和迭代(iterables)是什么? 你知道什么是内置迭代器吗? #547

Open
Rashomon511 opened this issue Jul 16, 2019 · 0 comments

Comments

@Rashomon511
Copy link
Owner

Rashomon511 commented Jul 16, 2019

迭代(Iteration )是什么,它分为两个部分
Iterable:可迭代性是一种数据结构,它希望使其元素可以访问公共部分。它通过内置系统的一个方法,键为 Symbol.iterator。这个方法就是迭代器的工厂。
Iterator:用于遍历数据结构的元素的指针

内置可迭代对象
1)数组Arrays

console.log([][Symbol.iterator])
 
for(let x of ['a','b'])
    console.log(x)

2)字符串Strings

console.log(""[Symbol.iterator])
for(let x of "abc")
    console.log(x)

3)Map

let map = new Map().set('a', 1).set('b', 2);
console.log(map[Symbol.iterator]);
for (let pair of map) {
	console.log(pair);
}

4)Set

let set = new Set().add('a').add('b');
for (let x of set) {
    console.log(x);
}

5)arguments

function printArgs() {
    for (let x of arguments) {
        console.log(x);
    }
}
printArgs('a', 'b');

6)Typed Arrays

7)Generators,后面讲这个的时候在介绍

然后我们在看看哪些操作符以及表达式中可以操作迭代器

1)数组解构操作符

let set = new Set().add('a').add('b').add('c');//Chrome浏览器不支持这段代码
let [x,y] = set;

let [first, ...rest] = set;

2)for-of循环

3)Array.from,新添加的数组静态方法

Array.from(new Map().set(false, 'no').set(true, 'yes'))

4)spread操作符

let arr = ['b', 'c'];
['a', ...arr, 'd']

5)Map,Set构造函数
let map = new Map([['uno', 'one'], ['dos', 'two']]);
let set = new Set(['red', 'green', 'blue']);

6)Promise.all,Promise.race参数

7)yield*
https://www.jianshu.com/p/2d0187f30a54

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant