我继承了我正在从事的项目的一些代码,并且经常看到使用这种语法
let arrayAsObject = [];
arrayAsObject.foo = 'bar';
console.log(arrayAsObject.foo); //bar
console.log(Array.isArray(arrayAsObject)); //true
我以前从未见过像对象一样处理数组,我想知道上面的代码和这个在功能上有什么区别
let pojo = {};
pojo.foo = 'bar';
console.log(pojo.foo); //'bar'
console.log(Array.isArray(pojo)); //false
除了 pojo 显然不是数组之外,这种方式与另一种方式相比有什么好处吗?我倾向于使用对象,因为我一直都是这样做的,并且看到它完成的方式,这是我第一次看到用数组来代替它们。
最佳答案
JavaScript 中的通用数组根本不是真正的数组(除非优化),它们是继承自 Array.prototype 的对象,处理一类属性名称(“数组索引”*)特别地(嗯,有点),并且有一个特殊的 length
属性。就是这样。 (JavaScript 现在也有 typed arrays 形式的真正数组,但我们这里谈论的是通用的 [...]
数组。)
With the exception that the pojo is clearly not an array, is there any benefit from doing it one way vs the other.
将非索引属性添加到数组正式上是没问题的(毕竟,它们是对象),但是:
可能(或可能不会)导致 JavaScript 引擎取消优化数组。这仅在数组查找性能很重要的极少数情况下才重要。
在您之后维护代码的人可能会感到惊讶。
虽然它使分配的对象数量加倍,但为了避免这些问题但仍然携带额外的信息,您可以考虑将数组作为属性的对象:
let obj = {
foo: "bar",
data: []
};
console.log(obj.foo); //bar
console.log(Array.isArray(obj.data)); //true
这允许数组成为一个没有无关信息的数组,同时仍然将额外信息 (foo
) 与它分组。
或者您可以接受具有非索引属性的数组。这取决于你。
<小时/>* “数组索引” - 来自 the specification :
An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253-1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232-1.
关于javascript - 带点赋值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46288299/