Checking whether something is iterable

后端 未结 8 903
甜味超标
甜味超标 2020-11-28 04:55

In the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

The for...of construct is described to be able to

8条回答
  •  清酒与你
    2020-11-28 05:13

    As a sidenote, BEWARE about the definition of iterable. If you're coming from other languages you would expect that something you can iterate over with, say, a for loop is iterable. I'm afraid that's not the case here where iterable means something that implements the iteration protocol.

    To make things clearer all examples above return false on this object {a: 1, b: 2} because that object does not implement the iteration protocol. So you won't be able to iterate over it with a for...of BUT you still can with a for...in.

    So if you want to avoid painful mistakes make your code more specific by renaming your method as shown below:

    /**
     * @param variable
     * @returns {boolean}
     */
    const hasIterationProtocol = variable =>
        variable !== null && Symbol.iterator in Object(variable);
    

提交回复
热议问题