Title Please explain the output of the following statement:
x = {shift:[].shift};
x.shift();
console.info(x.length);
If you answered correctly , then it means that you already understand the generic application of Array function. Before understanding this question, we must first understand the definition of shift for an array (Array).
The relevant instructions have been described very clearly in MDC
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 length property of the object for the shift operation. So basically we can understand that the answer to the above question is
0
Diffusion thinking
If you still can’t understand the above question, then we can explain more clearly the impact of Array.prototype.shift on the length of the object.
x = {};
Array.prototype. shift.call(x);
console.info(x.length);
Obviously, if the length attribute is defined for an object, shift will automatically add the length attribute and set it is 0.
Now that we have said this, let’s leave it to everyone to think about what to output in the following questions.
x = function (a, b, c) {} ;
Array.prototype.shift.call(x);
console.info(x.length);
Reunderstanding generics
Obviously, the above question has Maybe I still can’t explain the title of this article. Generic applications have actually been explained before, but here we mainly explain the use of the Array method for "array-like" operations.
Force to array
var args = Array.prototype.slice.call(arguments);
This usage is more Martian, but it has also been used before this period. See here for details.
Iterate data
Array.prototype.forEach.call(arguments, function(i) {
console.info(i);
});
If the object can be recursed, then exit 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). Array’s forEach method is detailed here.
Other Array extension usage can spread your own ideas. If there is no corresponding implementation method for Array in the corresponding browser, you can refer to here.
In fact, not only the Array method, but also the methods of many browser native objects are generic. We can completely use these features to make the code clearer.
Using native methods is more efficient.