Checking whether something is iterable

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

    The proper way to check for iterability is as follows:

    function isIterable(obj) {
      // checks for null and undefined
      if (obj == null) {
        return false;
      }
      return typeof obj[Symbol.iterator] === 'function';
    }
    

    Why this works (iterable protocol in depth): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols

    Since we are talking about for..of, I assume, we are in ES6 mindset.

    Also, don't be surprised that this function returns true if obj is a string, as strings iterate over their characters.

提交回复
热议问题