Class array object in JavaScript

  • 2020-05-27 04:13:38
  • OfStack

I knew long ago that I could convert arguments to an array: [] (arguments), because
arguments is an array of class objects, so you can use it this way. But I don't know what a class array object is (array-like objects)

Today, Effective JavaScript has a special section on this, which is really a drag.

Take a look at some sample code I wrote:

a = "hello"
[], (e) -> e.toUpperCase()) # => [ 'H', 'E', 'L', 'L', 'O' ]
[], (acc, e) -> acc + e) # => 'olleh'
b = {1: "a", 2: "b", 4: "c", length: 6}
[], (acc, e) -> acc + e) # => 'abc'

The first few are manipulation strings, well, strings can also be viewed as array like objects. But the b object in the back is amazing
Also an array of class objects.

The explanation in the book:

So what exactly makes an object " array-like " ? The basic contract of
an array object amounts to two simple rules.
It has an integer length property in the range 0...2^32 � 1.
The length property is greater than the largest index of the object.
An index is an integer in the range 0...2^32 � 2 whose string representation
is the key of a property of the object.

There are only two simple rules.

So why can arguments, string, and the b object above be treated as an array of class objects?

They all have a valid length attribute (a positive integer between 0 and 2**32-1).
The value of the length properties is greater than their maximum index (index).
Here's another example:

b = {1: "a", 2: "b", 4: "c", length: 3}
[], (acc, e) -> acc + e) # => 'ab'

Well, it's not right, it's 'ab', because it violates rule 2: length property is 3,
The maximum index value is 4 which is larger than the length attribute. So it's not acting normally.

It is so powerful that it seems like there is only one interface defined, and as long as it conforms to that interface, you can take advantage of all the methods in the array.

Well, not all of them, Array.prototype.concat
You can't use it, because it's concatenating two arrays, you can't use it without an array.

Another minor problem is that strings are immutable after they are created (immutable), so whatever you do with them is immutable.

But the book doesn't even explain why these two conditions apply to an array like object, and the author of the book
It's a member of the ECMAScript committee, so it's pretty credible. As for why these two conditions can be regarded as an array object, I do not know, Google searched for a long time also did not see any reasonable explanation.

That's all for this article, I hope you enjoy it.

Related articles: