SoFunction
Updated on 2025-03-01

Analysis of generic applications

topic
Please specify the output of the following statement:
Copy the codeThe code is as follows:

x = {shift:[].shift};
();
();

If you answer correctly, then you already know about the generic application of the Array function. Before understanding this to the question, I first need to understand the shift definition of an array (Array).

The relevant description has been described very clearly in the MDC
Copy the codeThe code is as follows:

shift is intentionally generic; this method can be called or
applied to objects resembling arrays. Objects which do not
contain a length property reflecting the last in a series of
consecutive, zero-based numerical properties may not behave
in any meaningful manner.

At the same time, the definition in EMCAScript also defines the change of the object length attribute for shift operations. Basically, we can understand that the answer in the previous question is
Copy the codeThe code is as follows:
0

Diffusion thinking
If the above question is not yet understood, then we will explain more clearly the impact on the length of the object.
Copy the codeThe code is as follows:

x = {};
(x);
();

Obviously, if the length attribute is defined for an object, shift will automatically add the length attribute and set to 0 .

Since we have already said this, what is the following question output for everyone to think about?
Copy the codeThe code is as follows:

x = function (a, b, c) {};
(x);
();

Re-understand generics
It is obvious that the above topic may not explain the title of this article. Generic applications have actually been explained before the period, but here we mainly explain the use of the Array method for the operation of "class arrays".

Casting to an array
Copy the codeThe code is as follows:

var args = (arguments);

This usage is more than Mars, and I have actually used it before the period, so please refer to it here for details.

Iterate data
Copy the codeThe code is as follows:

(arguments, function(i) {
(i);
});

If the object can be recursive, in addition to the "traditional" for, while and other statements, you can also consider using the forEach attribute of Array (note that IE will be a tragedy). For details on Array's forEach method, please see here.

Other Array extension usages can exude your own thinking. If the corresponding browser Array does not have a corresponding implementation method, you can refer to this.

In fact, it is not just the Array method, many browser native object methods are generics, and we can completely use these features to make the code clearer.
Using native methods is more efficient.