JavaScript pseudo Array Implementation method _javascript techniques

Source: Internet
Author: User
Tags arrays numeric value
This article answers the last mentioned questions about pseudo arrays in the JavaScript Universal loop Traversal method foreach.
What is a pseudo array
An object with the length property that can be converted to a true array via Array.prototype.slice.
There are a lot of these objects, more specifically arguments objects, and like Call Getelementsbytagname,document.childnodes, which return nodelist objects are pseudo arrays.
We can turn the pseudo array into a true array object by Array.prototype.slice.call (Fakearray).
Let's look at an example:
Copy Code code as follows:

var fakeArray01 = {0: ' A ', 1: ' B ', length:2};//This is a standard have pseudo array object
var Arr01 = Array.prototype.slice.call (FAKEARRAY01);
Alert (arr01[0]);//a
var arr02 = [].slice.call (FAKEARRAY01);
Alert (arr02[0]);//a

Slice can be used to get an array fragment, which returns a new array and does not modify the original array.
In the example, you can see that Fakearray was successfully converted to an array object. Perhaps everyone to Array.prototype.slice.call this kind of writing is unfamiliar, in fact we can also pass []. Slice.call this form to achieve the same effect, then why do we have to implement the form of prototype, the answer is in the form of prototype execution of the program more efficient, the same code is more beautiful.
Implementation of Pseudo-array
let's take a closer look at the implementation of the pseudo array.
Let's look at some special use cases:
Copy Code code as follows:

var fakeArray01 = {A: ' A ', B: ' B ', length:2};//no value corresponding to length subscript
var Arr01 = Array.prototype.slice.call (FAKEARRAY01);
Alert (arr01[0]);//undefined
var fakeArray02 = {0: ' A ', 1: ' B ', length: ' num '};//length not numeric
var arr02 = Array.prototype.slice.call (fakeArray02);
Alert (arr02[1]);//undefined

Similarly fakeArray01 and fakeArray02 are converted to real arrays, but the values in the array are undefined
View V8 engine Array.js Source, you can simplify the internal implementation of slice to:
Copy Code code as follows:

function slice (start, end) {
var len = ToUint32 (this.length), result = [];
for (var i = start, I < end; i++) {
Result.push (This[i]);
}
return result;
}

As you can see, slice does not need this as the array type, only the length attribute is required. And the length property can be not a number type, and ToUnit32 (this.length) returns 0 when it cannot be converted to a numeric value.
According to the above conclusions: FAKEARRAY01 is converted to an array of Lenth 2, whose values are initialized to UNDEFINED,FAKEARRAY02 are converted to an array of length 0, and the element of natural access subscript 1 returns undefined
The problem of IE
The slice implementation of the standard browser can already explain all the problems, but IE has a problem with nodelist. An error occurs when IE cannot convert nodelist to a true array. Why is that? Strictly speaking, in IE internal definition of an abstract class Arraioid,array and arguments are inherited with this, so you can use slice. However, Dom objects are accessed via COM to JScript, and slice are invalidated when detected.
jquery and pseudo arrays
A lot of pseudo arrays are used inside jquery. It can be said that the entire jquery object is built on the basis of pseudo arrays, so let's look at some of the practical uses of jquery:
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<title>fakeArray</title>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<script src= "Jquery-1.4.2.js" type= "Text/javascript" ></script>
<script>
$ (document). Ready (function () {
var BODY = $ ("body");
Alert (body.get (0). TagName);
});
</script>
<body>
<div id= "Test" ></div>
</body>

The simple procedure, OK, let's take a look at its internal implementation principle:
Copy Code code as follows:

Jquery.fn = Jquery.prototype = {
Init:function (Selector, context) {
var match, Elem, ret, doc;
Handle $ (""), $ (null), or $ (undefined)
if (!selector) {
return this;
}
Handle $ (domelement)
if (Selector.nodetype) {
This.context = this[0] = selector;
This.length = 1;
return this;
}
The BODY element is only exists once, optimize finding it
if (selector = = "Body" &&!context) {
This.context = document;
This[0] = document.body;
This.selector = "Body";
This.length = 1;
return this;
}
//... ...
},
Get:function (num) {
return num = null?
Return a ' clean ' array
This.toarray ():
Return just the object
(Num < 0 this.slice (num) [0]: this[num]);
}
}

Finally, let's explain the details of the execution of the program. But before that, you have to say something about the internals of jquery.
Users who have used jquery should know the $ () function, which is the selector representative of jquery. We may use the $ () function to select the elements in the page (the specific syntax can be parameter jquery Help document). In fact, when we execute the $ () function, the program executes the Init method listed above, and we look at the event that occurs when the $ (document) is invoked:
Copy Code code as follows:

$ (document)
Init:function (Selector, context) {
var match, Elem, ret, doc;
Handle $ (domelement): Handles DOM elements,
if (Selector.nodetype) {
This.context = this[0] = selector; Give attribute 0 A selector value, which is the Document object
This.length = 1; Create pseudo array, update subscript
return this; Back to the JQuery object
}
//... ...
}

$ ("body") is the same truth, no longer said more.
We know that all the operations in jquery are returning jquery objects, so how do we get their corresponding DOM objects, jquery provides us with a getting method, which is specifically used to get DOM objects from the jquery object, and hence the body.get ( 0), then why get (0) instead of get (), because all of jquery's operations are for the array. So, in the Get method, we're going to pass a subscript value that gets the concrete element. Now it's time to look at the concrete implementation of the Get method:
Copy Code code as follows:

Get:function (num) {
return num = null?
If NUM is not, the DOM array is returned directly
This.toarray ():
If NUM is specified, the element that specifies the subscript is returned
This.slice is another way of jquery, which actually calls Array.prototype.slice to convert a pseudo array to a real array.
(Num < 0 this.slice (num) [0]: this[num]);
}

About pseudo arrays Here it is, I think it's almost done.
Note: In the future, there may be a "beyond jquery" series that will specifically analyze the internal details of the jquery implementation. But because of the various crooked methods inside jquery are not very understanding, so this is a future problem.
Reference:
http://lifesinger.org/blog/2010/05/array-prototype-slice/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.