在注释中指出:


  可迭代协议允许JavaScript对象定义或自定义
  它们的迭代行为,例如在一个值中循环了哪些值
  for..of结构。


当我已经可以使用时,我看不到有什么好处:Object.degineProperty可以枚举。

function withValue(value) {
       var d = withValue.d || (
           withValue.d = {
               enumerable: false,
               writeable: false,
               configuration: false,
               value: null
          }
      )
    // other code;
   }


这些协议有什么好处?如果这只是一种新的语法来安抚新的for ... of循环,则除了简单地检查长度并查看其是否用完了“列表”中的项目外,它还有什么好处。

最佳答案

将Iterable视为接口。您可以放心,实现中包含Symbol.iterator属性,该属性实现了next()方法。如果实现自己,则可以在运行时生成要迭代的值。举一个简单的例子,生成一个列表,然后决定以后要迭代多少个(或哪个或任何条件):

function List (...args) {
    this.getOnly = function (limit) (
        const effectiveLimit = Math.min(args.length, limit + 1);
        const iterable = {
            [Symbol.iterator]() {
                let count = 0;
                const iterator = {
                    next() {
                        if (count < effectiveLimit) {
                            return { value: args[count++] };
                        } else {
                            return { done: true };
                        }
                    }
                };
                return iterator;
            }
        }
        return iterable;
    };
}

const list = List(0, 1, 2, 3, 4);
for (const x of list.getOnly(3)) {
    console.log(x);
}
// returns 0, 1, 2


如果您使用实现Iterable接口的Generator函数,则将变得非常简单:

function List (...args) {
    this.getOnly = function* (limit) {
        const effectiveLimit = Math.min(args.length, limit + 1);
        for (let count = 0; count < effectiveLimit; count++) {
            yield args[count];
        }
    }
}


here中列出了有关Iterables的更多示例。

09-11 14:47