【问题标题】:Yield of for...in element returns strings array [duplicate]for...in 元素的产量返回字符串数组 [重复]
【发布时间】:2021-05-17 13:30:45
【问题描述】:

我试图打印由yield 生成的数组,不知何故,如果我使用 for...in 语句,它会创建一个字符串数组,同时使用常规 for 循环它可以正常工作。
为什么会这样?

function *hello1(elements) {
    for(var el in  elements) yield el;
}
function *hello2(elements) {
    for(var i=0;i<elements.length;i++) yield elements[i];
}

var elements = [1,2,3];
console.log(elements);
console.log([...hello1(elements)]);
console.log([...hello2(elements)]);

【问题讨论】:

  • 谢谢大家,我不知道有什么区别

标签: javascript yield


【解决方案1】:

您的意思是使用for...of,而不是for...in,后者用于迭代目标对象的可枚举键。你也可以用yield*代替for...ofyield

function* hello1(elements) {
  for (var el of elements) yield el;
}

function* hello2(elements) {
  yield* elements;
}

var elements = [1, 2, 3];
console.log(elements);
console.log([...hello1(elements)]);
console.log([...hello2(elements)]);

【讨论】:

    【解决方案2】:

    要获取元素,需要取for ... of statement

    for ... in statement 迭代对象的键(不带符号)并返回字符串。

    function* hello1(elements) {
        for (var el of elements) yield el;
    }
    
    var elements = [1, 2, 3];
    
    console.log([...hello1(elements)]);

    更短的方法只返回数组作为可迭代 yield* expression

    function* hello1(elements) {
        yield* elements;
    }
    
    var elements = [1, 2, 3];
    
    console.log([...hello1(elements)]);

    【讨论】:

      猜你喜欢
      • 2016-09-25
      • 2020-05-25
      • 2019-07-18
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 2021-01-15
      • 2019-11-24
      • 2013-10-26
      相关资源
      最近更新 更多