为什么Object.assign使用数组? [英] Why Object.assign works with an array?

查看:889
本文介绍了为什么Object.assign使用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在阅读一篇文章,以克隆对象和数组.他们所有人都提到Object.assign()可用于复制对象,但没有人提到Object.assign()也可用于浅复制数组.

So I was reading an article to clone an object and array. All of them mentioned that Object.assign() can be used to copy an object but no one mentioned that Object.assign() will also work to shallow copy an array.

有人可以解释它的工作原理吗?

Could anybody explain how it works?

Code to Explain is in JS Bin : https://jsbin.com/kaqocixize/edit?js,console

推荐答案

JS是面向原型的语言. 这意味着JS中的每个构造都是现实的-一个对象! :)

JS is prototype-oriented language. That means that every construct in JS is in reality - an object! :)

对象在某些元数据中有所不同,例如具体属性.这些通常是只读的,没有覆盖它们的简便方法(例如length, name, arguments等).

Objects differ in some metadata, e.g. specific properties. These are usually readonly and there is no easy way of overriding them (e.g. length, name, arguments and many more).

在您的情况下,数组可以解释为特定对象,其中length与数组元素的数量有关,每个数组元素与使用索引作为键的对象的属性有关:

In your case, array can be interpreted as a specific object where length relates to number of array elements and each array element relates to property on the object that uses index as a key:

const array = {
  '0': 'a',
  '1': 'b',
  '2': 'c',
  'length': 3,
};

(这很简单,因为我们仍然缺少用于迭代的生成器,通常将其保留为Symbol).

(that's simplification, as we're still missing generator for iterating over that is usually kept as a Symbol).

JS隐藏这些特殊属性的方式通常是使用符号-在此处进行更多的了解: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol

The way JS hides these special properties is usually by using Symbols - more on them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

但是,由于JS的原型性质,当使用Object.assign时,通过执行以下操作将Array视为对象,

Because of prototypic nature of JS, however, when using Object.assign, Array is treated as an object and hence, by doing:

Object.assign([],a,['x']); 

您实际上是在创建一个新数组 AND ,并用'x'覆盖元素0.这就是在对象世界中可以解释这一行的方式:

you're actually creating a new array AND overriding element 0 with 'x'. That's how this line can be interpreted in object world:

Object.assign({}, {
  '0': 'a',
  '1': 'b',
  '2': 'c',
}, {
  '0': 'x'
});

这就是x作为新数组的第一个索引登陆的方式!

And that's how x landed as the first index of a new array!

但是,ES5和ES6之间在Array实现方面存在一些差异-有关更多信息,请参见: http://2ality.com/2014/05/es6-array-methods.html

There are, however, some differences in Array implementation between ES5 and ES6 - more on that here: http://2ality.com/2014/05/es6-array-methods.html

这篇关于为什么Object.assign使用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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