Array.prototype[@@iterator]() - JavaScript 编辑

The @@iterator method is part of The iterable protocol, that defines how to synchronously iterate over a sequence of values.

The initial value of the @@iterator property is the same function object as the initial value of the values() property.

Syntax

arr[Symbol.iterator]()

Return value

The initial value given by the values() iterator. By default, using arr[Symbol.iterator] will return the values() function.

Examples

Iteration using for...of loop

HTML

<ul id="letterResult">
</ul>

JavaScript

const arr = ['a', 'b', 'c'];
const eArr = arr[Symbol.iterator]();
const letterResult = document.getElementById('letterResult');
// your browser must support for..of loop
// and let-scoped variables in for loops
// const and var could also be used
for (let letter of eArr) {
  const li = document.createElement('LI');
  li.textContent = letter;
  letterResult.appendChild(li);
}

Result

Alternative iteration

var arr = ['a', 'b', 'c', 'd', 'e'];
var eArr = arr[Symbol.iterator]();
console.log(eArr.next().value); // a
console.log(eArr.next().value); // b
console.log(eArr.next().value); // c
console.log(eArr.next().value); // d
console.log(eArr.next().value); // e

Use Case for brace notation

The use case for this syntax over using the dot notation (Array.prototype.values()) is in a case where you don't know what object is going to be ahead of time. If you have a function that takes an iterator and then iterate over the value, but don't know if that Object is going to have a [Iterable].prototype.values method. This could be a built-in object like String object or a custom object.

function logIterable(it) {
 if (!(Symbol.iterator in Object.getPrototypeOf(it)
 /* or "Symbol.iterator in Object.__proto__"
    or "it[Symbol.iterator]" */)) {
   console.log(it, ' is not an iterable object...');
   return;
 }

 var iterator = it[Symbol.iterator]();
  // your browser must support for..of loop
  // and let-scoped variables in for loops
  // const and var could also be used
  for (let letter of iterator) {
      console.log(letter);
  }
}

// Array
logIterable(['a', 'b', 'c']);
// a
// b
// c

// string
logIterable('abc');
// a
// b
// c

logIterable(123);
// 123 " is not an iterable object..."

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'Array.prototype[@@iterator]()' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:68 次

字数:5808

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文