Checking whether something is iterable

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

    The simplest solution is actually this:

    function isIterable (value) {
      return Symbol.iterator in Object(value);
    }
    

    Object will wrap anything which isn't an object in one, allowing the in operator to work even if the original value is not an Object. null and undefined are turned into empty objects so there's no need for edge case detection, and strings get wrapped into String objects which are iterable.

提交回复
热议问题