为什么通过括号访问Symbol.iterator? [英] Why do you access Symbol.iterator via brackets?

查看:36
本文介绍了为什么通过括号访问Symbol.iterator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我创建了一个数组,则 var array = [1,2,3,4]; 返回一个迭代器,我会做 var iterator = array [Symbol.iterator](); 我不明白为什么您要通过方括号访问Symbol.iterator属性?为什么不只是 array.Symbol.iterator ?

If I created an array, for instance, var array=[1,2,3,4]; to return an iterator I would do var iterator = array[Symbol.iterator](); I don't understand why you access the Symbol.iterator property through brackets? Why isn't it just array.Symbol.iterator?

推荐答案

名为 Symbol 的数组上没有属性(除非您在其中放置了一个).取而代之的是,您正在查找谁的键值是 Symbol.iterator 指向的符号原语. Symbol.iterator 返回一个符号,然后您将该符号用作查找键.就像在查找带有变量的属性一样:

There is no property on an array called Symbol (unless you put one there). Instead you are looking up up the values who's key is the symbol primitive that Symbol.iterator points to. Symbol.iterator returns a symbol and you use that symbol as the lookup key. It's a little like looking up a property with a variable:

let a = [1, 2, 3]
a.someProp = "hello"

let key = "someProp"

// this doesn't work for the same reason s.Symbol.iterator doesn't:
// a.key

// but this does:
console.log(a[key])

// So with a Symbol:

let k = Symbol.iterator
console.log(typeof k)
// k is now a reference to the symbol that is the key
// you can use that to returns the iterator function
console.log(a[k])    // <-- that returns your iterator function
console.log([...a[k]()])

// equivalent to:
console.log([...a[Symbol.iterator]()])

这篇关于为什么通过括号访问Symbol.iterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆