haizlin / fe-interview

前端面试每日 3+1,以面试题来驱动学习,提倡每日学习与思考,每天进步一点!每天早上5点纯手工发布面试题(死磕自己,愉悦大家),6000+道前端面试题全面覆盖,HTML/CSS/JavaScript/Vue/React/Nodejs/TypeScript/ECMAScritpt/Webpack/Jquery/小程序/软技能……

Home Page:http://www.h-camel.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[js] 第660天 js中Iterable对象和Array有什么区别?

haizhilin2013 opened this issue · comments

第660天 js中Iterable对象和Array有什么区别?

3+1官网

我也要出题

  • iterable对象是符合迭代器接口,可以通过 iterable.next()或者 for of 访问其中的元素
  • Array是特殊的iterable对象,除了itearable的方式不遍历外,还 提供了 for in foreach map等方式

iterable协议定义: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

Array 是内置iterable协议的可迭代对象,因为在原生实现了[Symbol.iterator]函数,除Array之外还有Set, Map, String等等内置实现iterable协议的可迭代对象.

  • iterable对象是符合迭代器接口,可以通过 iterable.next()或者 for of 访问其中的元素
  • Array是特殊的iterable对象,除了itearable的方式不遍历外,还 提供了 for in foreach map等方式

楼上回答可以通过iterable.next()或者for of访问元素稍有歧义,因为这是是通过调用可迭代对象的@@iterator方法产生的迭代器(iterator)的功能并不属于iterable.

具体解释
Whenever an object needs to be iterated (such as at the beginning of a for...of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.