Checking whether something is iterable

后端 未结 8 905
甜味超标
甜味超标 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:19

    Nowadays, as already stated, to test if obj is iterable just do

    obj != null && typeof obj[Symbol.iterator] === 'function' 
    

    Historical answer (no more valid)

    The for..of construct is part of the ECMASCript 6th edition Language Specification Draft. So it could change before the final version.

    In this draft, iterable objects must have the function iterator as a property.

    You can the check if an object is iterable like this:

    function isIterable(obj){
       if(obj === undefined || obj === null){
          return false;
       }
       return obj.iterator !== undefined;
    }
    
    0 讨论(0)
  • 2020-11-28 05:22

    For async iterators you should check for the 'Symbol.asyncIterator' instead of 'Symbol.iterator':

    async function* doSomething(i) {
        yield 1;
        yield 2;
    }
    
    let obj = doSomething();
    
    console.log(typeof obj[Symbol.iterator] === 'function');      // false
    console.log(typeof obj[Symbol.asyncIterator] === 'function'); // true
    
    0 讨论(0)
提交回复
热议问题