Http://www.gracecode.com/archives/3023/
Before starting this article, follow the "Conventions" to explain the question (source) first ).
Question
Describe the output of the following statement:
x = {shift:[].shift};x.shift();console.info(x.length);
If the answer is correct, it indicates that you have understood the generic applications of array functions. Before understanding this question, we should first understand the shift definition of arrays.
The description of MDC is very clear.
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 changes to the Length attribute of the object for the shift operation, so we can basically understand that the answer to the above question is
0
Diffuse thinking
If you still cannot understand the above questions, we will be more clear about the impact of array. Prototype. Shift on the object length.
x = {};Array.prototype.shift.call(x);console.info(x.length);
Obviously, if an object defines the Length attribute, shift will automatically add the Length attribute and set it0.
Now that we have already mentioned this, let us think about the output of the following questions.
x = function (a, b, c) {};Array.prototype.shift.call(x);console.info(x.length);New Understanding of generics
Obviously, the above questions may not be able to explain the questions in this article. The generic (generic) application also described before the actual period, but here mainly describes the use of the array method for "class array" operations.
Forced conversion to array
var args = Array.prototype.slice.call(arguments);
This usage is similar to that of Mars. It was used before the actual period. For details, see here.
Iterative data
Array.prototype.forEach.call(arguments, function(i) { console.info(i);});
If the object can be recursive, you can also consider using the foreach attribute of array in addition to the "traditional" for, while and other statements (note that IE is a tragedy ). For the array foreach method, see here.
Other extended array usage can give away your own thinking. If the array corresponding to the browser does not have the corresponding implementation method, see here.
In fact, not only the array method, but many native browser object methods are generic. We can fully use these features.
- Make the code clearer
- The native method is more efficient.
-- EOF --