Checking whether something is iterable

后端 未结 8 926
甜味超标
甜味超标 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;
    }
    

提交回复
热议问题