Class array objects in JavaScript, javascript Array
A long time ago, I knew that I could convert arguments to an array: []. slice. call (arguments) because
Arguments is a class array object, so this can be used. But I still don't know what it is called array-like objects)
Today, I have a special article on objective JavaScript, which is really a drag-and-drop.
Let's take a look at some sample code I have written:
Copy codeThe Code is as follows:
A = "hello"
[]. Map. call (a, (e)-> e. toUpperCase () # => ['h', 'E', 'l', 'l', 'O']
[]. ReduceRight. call (a, (acc, e)-> acc + e) # => 'olleh'
B = {1: "a", 2: "B", 4: "c", length: 6}
[]. Reduce. call (B, (acc, e)-> acc + e) # => 'abc'
The first few are operation strings. Well, strings can also be seen as class array objects. But the next B object is actually
It is also a class array object.
Reading explanation:
Copy codeThe Code is as follows:
So what exactly makes an object "array-like "? The basic contract
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 above B object be considered as a class array object?
They all have a valid length attribute (a positive integer between 0 and 2 ** 32-1 ).
The value of the length attribute is greater than their maximum index ).
Another example:
Copy codeThe Code is as follows:
B = {1: "a", 2: "B", 4: "c", length: 3}
[]. Reduce. call (B, (acc, e)-> acc + e) # => 'AB'
Well, it's wrong. It's 'AB' because it violates Rule 2: The length attribute is 3,
The maximum index value is 4, which is greater than the length attribute. So the performance is abnormal.
It seems that an interface is defined, and all methods of the array can be used as long as it complies with the interface.
In fact, not all methods can be used, Array. prototype. concat
It cannot be used because it connects two arrays. You cannot use it if you are not an array.
Another small problem is that the string is immutable after it is created, so it is immutable.
However, this book does not explain why the two conditions are met and can be considered as an array object of classes. In addition, the author of this book
The members of the ECMAScript Committee are basically credible. I don't know why the two conditions can be regarded as a class array object. Google hasn't seen any reasonable explanation after searching for a long time.
The above is all the content of this article. I hope you will like it.