美文网首页
ES6(八)迭代器与生成器3

ES6(八)迭代器与生成器3

作者: 蒋小花_4b6c | 来源:发表于2020-05-28 19:08 被阅读0次

1.扩展运算符与非数组的可迭代对象

2.传递参数给迭代器

扩展运算符与非数组的可迭代对象

扩展运算符( ... )可以被用于将一个 Set 转换为数组:

let set = new Set([1, 2, 3, 3, 3, 4, 5]),

array = [...set];

console.log(array);

用于任意的可迭代对象:

let map = new Map([ ["name", "Nicholas"], ["age", 25]]),

array = [...map];

console.log(array);

在任意位置用扩展运算符将可迭 代对象的多个项插入数组:

let smallNumbers = [1, 2, 3],

    bigNumbers = [100, 101, 102],

    allNumbers = [0, ...smallNumbers, ...bigNumbers];

console.log(allNumbers.length);

console.log(allNumbers);    // [0, 1, 2, 3, 100, 101, 102]

传递参数给迭代器

function *createIterator() {

    let first = yield 1;

    let second = yield first + 2;

    yield second + 3;

}

let iterator = createIterator();

console.log(iterator.next());

console.log(iterator.next(4));

console.log(iterator.next(5));

console.log(iterator.next());

使用 return 让生成器更早返回:

function *createIterator() {

    yield 1;

    return;

    yield 2;

    yield 3;

}

let iterator = createIterator();

console.log(iterator.next());

console.log(iterator.next());

指定一个返回值:

function *createIterator() {

    yield 1;

    return 42;

}

let iterator = createIterator();

console.log(iterator.next());

console.log(iterator.next());

console.log(iterator.next());

生成器委托

在某些情况下,将两个迭代器的值合并器一起用:

function *createNumberIterator() {

    yield 1;

    yield 2;

}

function *createColorIterator() {

    yield "red";

    yield "green";

}

function *createCombinedIterator() {

    yield *createNumberIterator();

    yield *createColorIterator();

    yield true;

}

var iterator = createCombinedIterator();

console.log(iterator.next());   // "{ value: 1, done: false }"

console.log(iterator.next());   // "{ value: 2, done: false }"

console.log(iterator.next());   // "{ value: "red", done: false }"

console.log(iterator.next());   // "{ value: "green", done: false }"

console.log(iterator.next());   // "{ value: true, done: false }"

console.log(iterator.next());   // "{ value: undefined, done: true }"

相关文章

网友评论

      本文标题:ES6(八)迭代器与生成器3

      本文链接:https://www.haomeiwen.com/subject/xidwahtx.html