这个 Object.assign({}, ...array.map(/*...*/)) 代码在这里做什么
我已经从 github 克隆了这个存储库,但我无法理解代码中发生的情况。
代码中的words
是一个单词数组。
const wordDictionary = Object.assign({}, ...words.map((x) => ({ [x]: x })));
I have cloned this repo from github and I am unable to understand what's happening in the code.
words
in the code is an array of words.
const wordDictionary = Object.assign({}, ...words.map((x) => ({ [x]: x })));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它采用一个数组(字符串数组,因为您说它是单词数组;但它也可以使用数字或符号)并将其转换为属性名称和值都相同的对象。例如,
["an", "example"]
变为{an: "an", example: "example"}
:它通过将每个数组元素映射到具有一个属性的对象(由数组元素命名,并带有数组元素的值),然后将所有这些对象分配给单个目标对象来实现这一点。
例如,对于我的
["an", "example"]
数组,步骤如下:<前><代码>[“一个”,“示例”]
进入
Object.assign
带有空白目标对象。所以变成
Object.assign
将这些对象的属性分配给第一个对象(空白{}
对象)。值得注意的是,代码过于复杂。使用循环会更简单:
单独地,这样的字典可以通过
Map
实例:或者在这种特定情况下(因为键和值相同)
设置
:It's taking an array (of strings, since you said it's an array of words; but it would work with numbers or Symbols too) and converting it to an object where both the names and values of the properties are the same. So for example,
["an", "example"]
becomes{an: "an", example: "example"}
:It does it by mapping each array element to an object with one property (named by the array element, with the value of the array element) and then assigning all of those objects to a single target object.
For instance, with my
["an", "example"]
array, the steps are:into
Object.assign
with a blank target object. Sobecomes
Object.assign
to assign the properties from those objects to the first one (the blank{}
object).It's worth noting that the code is overcomplicated. It would be much simpler just to use a loop:
Separately, dictionaries like this are better handled by
Map
instances:or in this specific case (since the key and value are the same) a
Set
: