JavaScript array objects using summary _javascript tips

Source: Internet
Author: User
Tags arrays iterable javascript array
The JavaScript array is essentially an object that converts the subscript of an array into a string and uses it as a property, so it is significantly slower than a real array, but it can be used more easily.

Change oneself pop,push,reverse,shift,sort,splice,unshift, do not change oneself concat,join,slice,indexof,lastindexof (the latter two is 1.6), 1.6 New iterators: map,filter,foreach,every,some,1.8 new Reduce,reduceright
method of Array object

Ff:firefox, N:netscape, Ie:internet Explorer
Method Description FF N IE
Concat () Adds a new element to a copy of the array, returns the new array, and the original array is unaffected 1 4 4
Join () Put all the elements of an array into a string. element is delimited by the specified delimiter. 1 3 4
Pop () Deletes and returns the last element of the array 1 4 5.5
Push () Adds one or more elements to the end of the array and returns a new length. 1 4 5.5
Reverse () Reverses the order of elements in an array. 1 3 4
Shift () Deletes and returns the first element of the array 1 4 5.5
Slice () Returns the selected element from an existing array 1 4 4
Sort () The elements of an array are sorted, with an optional argument, which is the comparison function. 1 3 4
Splice () Deletes the element and adds a new element to the array. 1 4 5.5
Tosource () Represents the source code for an object 1 4 -
ToString () Converts the array to a string and returns the result. 1 3 4
toLocaleString () Converts the array to a local array and returns the result. 1 3 4
Unshift () Adds one or more elements to the beginning of the array and returns a new length. 1 4 6
ValueOf () Returns the original value of an array object 1 2 4

Array object's Properties

Method Description FF N IE
Index 1 3 4
Input The input property is not available in a normal array, and only the array returned after calling the match () method of the string object has the input property. It is used to store the contents of the original string before the match. 1 3 4
Length Sets or returns the number of elements in the array. 1 2 4
Let's take a look at array cloning, which is now recognized as the fastest to clone arrays with Concat (). Here are some tests for direct traversal replication, Array.slice (0) and Array.concat ()
<script> var Aarr = new Array (100001). Join (' a '). Split ("); var d = new Date (); var bArr = []; for (var i = 0; i < aarr.length i++) {barr[i] = Aarr[i]; Alert (new Date ()-D); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

<script> var Aarr = new Array (100001). Join (' a '). Split ("); var d = new Date (); var bArr = aarr.slice (0); Alert (new Date ()-D); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

<script> var Aarr = new Array (100001). Join (' a '). Split ("); var d = new Date (); var bArr = Aarr.concat (); Alert (new Date ()-D); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Determines whether the object referenced by a variable is an array.
Copy Code code as follows:

var IsArray = function (a) {
Return a &&
typeof a = = = ' object ' &&
typeof a.length = = ' Number ' &&
typeof A.splice = = ' function ' &&
! (a.propertyisenumerable (' length '));
}

It is also common to have an array of computational power, not for special reports on accounting.
Copy Code code as follows:

Function.prototype.method = function (Name,func) {
This.prototype[name] = func;
return this;
}
Array.method (' Reduce ', function (fn,value) {
for (Var i=0,l=this.length;i<l;i++) {
Value = fn (this[i],value);
}
return value;
});

How to use, we can create a numeric array and related arithmetic functions, and put them into the reduce function.
Copy Code code as follows:

var data = [4,8,10,12,16]
var add = function (a,b) {
return a+b;
}
var mult = function (a,b) {
return a*b;
}
Use
var sum = data.reduce (add,0)
var product = Data.reduce (mult,1);

Each method to let the element execute the incoming method one by one. JAVASCRIPT 1.6 has implemented the corresponding foreach method, but IE does not support, people have made a similar each method, in each large class library has a corresponding implementation. Let's look at a nice implementation (the author is 51JS customer service fruit):
Copy Code code as follows:

Array.prototype.each = function (fn) {
for (var i=0;i <this.length;i++)
This[i].constructor==array?
This[i].each (FN):
Fn.call (This[i],i);
};
[1,[2,[3,[4,[5,[6,[7,[8,[9,[0]]]]]]]]]].each (
function () {
Return alert (this);
});

This is relatively powerful, in addition to the depth of the array can be traversed, but also to traverse the class array objects (such as Arguments,nodelist), all properties of the object will be called by the FN method. But in terms of design patterns, it takes up too much responsibility. Each method should be an array-oriented, and if it is an object or class array object, we should convert them to arrays, such as the makearray,mootools of jquery and the $a of prototype.
Copy Code code as follows:

var arrayize = function (iterable) {
try{
Return Array.prototype.slice.call (iterable);
}catch (e) {
var L = Iterable.length | | 0, array = new Array (l);
while (l--) array[l] = Iterable[l];
return array;
}
}

Then we can implement each function of the pure array.
Copy Code code as follows:

var each = function (func, array) {
for (var i=0,l = array.length; i<l; ++i) {
Func (Array[i])
}
}

And then change it to a prototype method.
Copy Code code as follows:

Array.prototype.each = function (func) {each (func,this);};

However, if the browser supports the javascript1.6 foreach method, use the Foreach
Copy Code code as follows:

Array.prototype.each = function (func) {
if (Array.prototype.forEach) {
This.foreach (func);
}else{
each (func,this);
}
};

Usage:
Copy Code code as follows:

[4, 5, 6].each (function (index) {alert (index + "+2 =" + (index+2));})

Firefox website also has a realization:
Copy Code code as follows:

if (! Array.prototype.forEach)
{
Array.prototype.forEach = function (Fun/*, thisp*/)
{
var len = this.length >>> 0;
if (typeof fun!= "function")
throw new TypeError ();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
Fun.call (Thisp, this[i], I, this);
}
};
}

Let's take a look at the concrete implementation of each method provided by jquery
Jquery.each (Obj,fn,arg)
The method has three parameters: the object obj to operate, the function FN to operate, and the function's parameter args.
Let's discuss it according to the OJB object:
1.obj objects are arrays
Each method invokes the FN function of the neutron element of the array, until the result returned by a call to a child element is false, that is, we can exit each method call when the supplied FN function is processed so that it satisfies a certain condition. When the arg argument is supplied by the each method, the argument passed in by the FN function is arg, otherwise: the child element Index, the child element itself.
2.obj object is not an array
The biggest difference between this method and 1 is that the FN method is carried out without regard to the return value. In other words, all the properties of the Obj object are invoked by the FN method, even if the FN returns false. Calling incoming arguments is similar to 1.
Copy Code code as follows:

Jquery.each=function (obj, FN, args) {
if (args) {
if (obj.length = = undefined) {
for (var i in obj)
Fn.apply (obj, args);
}else{
for (var i = 0, ol = Obj.length i < ol; i++) {
if (fn.apply (obj, args) = = False)
Break
}
}
} else {
if (obj.length = = undefined) {
for (var i in obj)
Fn.call (obj, I, obj);
}else{
for (var i = 0, ol = obj.length, val = obj[0]; I < ol && Fn.call (val,i,val)!== false; val = Obj[++i]) {}
}
}
return obj;
}

Of particular note is that the specific invocation method of FN in each method does not take the form of a simple FN (i,val) or FN (args), but rather a fn.call (val,i,val) or fn.apply (Obj.args), which means that In your own implementation of FN, you can directly refer to an array or a child element of an object by using the this pointer. This approach is one of the most used implementations of jquery.
Copy Code code as follows:

Array.prototype.contains = function (obj) {
return This.indexof (obj)!=-1;
};
Array.prototype.copy = function (obj) {
return This.concat ();
};
Array.prototype.insertAt = function (obj, i) {
This.splice (i, 0, obj);
};
Array.prototype.insertBefore = function (obj, obj2) {
var i = This.indexof (OBJ2);
if (i = = 1)
This.push (obj);
Else
This.splice (i, 0, obj);
};
Array.prototype.removeAt = function (i) {
This.splice (i, 1);
};
Array.prototype.remove = function (obj) {
var i = this.indexof (obj);
if (I!=-1)
This.splice (i, 1);
};
Related Article

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.