Javascript的数组实质是对象,它把数组的下标转换成字符串,用其作为属性,因此它明显比真正的数组慢,但它可以更方便地使用。
改变自身pop,push,reverse,shift,sort,splice,unshift, 不改变自身concat,join,slice,indexOf,lastIndexOf(后两个为1.6),1.6新增的迭代器:map,filter,forEach,every,some,1.8新增reduce,reduceRight
Array 对象的方法
FF: Firefox, N: Netscape, IE: Internet Explorer
方法 |
描述 |
FF |
N |
IE |
concat() |
向数组的副本添加新的元素,返回新的数组,原数组不受影响 |
1 |
4 |
4 |
join() |
把数组的所有元素放入一个字符串。元素通过指定的分隔符进行分隔。 |
1 |
3 |
4 |
pop() |
删除并返回数组的最后一个元素 |
1 |
4 |
5.5 |
push() |
向数组的末尾添加一个或更多元素,并返回新的长度。 |
1 |
4 |
5.5 |
reverse() |
颠倒数组中元素的顺序。 |
1 |
3 |
4 |
shift() |
删除并返回数组的第一个元素 |
1 |
4 |
5.5 |
slice() |
从某个已有的数组返回选定的元素 |
1 |
4 |
4 |
sort() |
对数组的元素进行排序,有一个可选参数,为比较函数。 |
1 |
3 |
4 |
splice() |
删除元素,并向数组添加新元素。 |
1 |
4 |
5.5 |
toSource() |
代表对象的源代码 |
1 |
4 |
- |
toString() |
把数组转换为字符串,并返回结果。 |
1 |
3 |
4 |
toLocaleString() |
把数组转换为本地数组,并返回结果。 |
1 |
3 |
4 |
unshift() |
向数组的开头添加一个或更多元素,并返回新的长度。 |
1 |
4 |
6 |
valueOf() |
返回数组对象的原始值 |
1 |
2 |
4 |
Array 对象的属性
>
方法 |
描述 |
FF |
N |
IE |
index |
|
1 |
3 |
4 |
input |
在普通的Array中是不具备input属性的,只有在调用String对象的match()方法后返回的数组才具有input属性。它是用来存放匹配前的原字符串的内容。 |
1 |
3 |
4 |
length |
设置或返回数组中元素的数目。 |
1 |
2 |
4 |
Let's look at array cloning first. It is now recognized that concat() is the fastest way to clone an array. Let’s do some tests, including direct traversal and copying, array.slice(0) and array.concat()
]
If you need to introduce external Js, you need to refresh to execute
]
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
Judge the object referenced by a variable Whether it is an array. Copy code
The code is as follows:
var isArray = function(a){
return a &&
typeof a === 'object' &&
typeof a.length === 'number' &&
typeof a.splice === 'function' &&
!(a.propertyIsEnumerable ('length'));
}
Let the array have calculation capabilities. This is also very commonly used and should not be used in special financial statements. Copy code
The code is 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;ivalue = fn(this[i],value);
}
return value;
});
How to use, we can create a number array and the four related arithmetic functions, and just substitute them into the reduce function Copy code
The code is 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, let the elements execute the passed in method one by one. The corresponding forEach method has been implemented in JavaScript 1.6, but IE does not support it. People have created a similar each method, which has corresponding implementations in major libraries. Let’s look at a beautiful implementation (the author is 51JS customer service Guoguo): Copy code
The code is as follows:
Array.prototype.each = function(fn){
for (var i=0;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);
});
The above is more powerful. In addition to deep traversal of arrays, it can also traverse array-like objects (such as arguments, NodeList). All properties of the object will be called by the fn method. But from the design pattern point of view, it has too many responsibilities. Each method should be array-oriented. If it is an object or array-like object, we should convert them into arrays, such as JQuery's makeArray, mootools and Prototype's $A. Copy code
The code is 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;
} <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>} <script>
var aArr = new Array(100001).join('a').split('');
var d = new Date();
var bArr = aArr.slice(0);
alert(new Date() - d);
</script><script>
var aArr = new Array(100001).join('a').split('');
var d = new Date();
var bArr = aArr.concat();
alert(new Date() - d);
</script>
Next we can implement the each function of a pure array.
var each = function(func, array) {
for (var i=0,l = array.length; ifunc(array[i])
}
}
Then again Change it to a prototype method
Array.prototype.each = function (func) { each(func,this); };
However, if the browser supports the forEach method of javascript1.6, use forEach
Array.prototype.each = function(func) {
if(Array.prototype.forEach){
this.forEach(func);
}else{
each(func,this);
}
};
Usage:
[4, 5, 6].each(function(index) { alert( index " 2 = " (index 2)); })
The Firefox official website also has an implementation:
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 us look at the specific implementation of each method provided by jQuery
jQuery.each(obj,fn,arg)
This method has three parameters: the object obj to be operated on, the function fn to be operated on, and the function parameters args.
Let us discuss based on the ojb object:
1. The obj object is an array
The each method will call the fn function one by one on the sub-elements in the array until the result returned by calling a certain sub-element is false. In other words, we can process it with the provided fn function and exit the each method call after it meets certain conditions. When the each method provides the arg parameter, the parameter passed in by the fn function call is arg, otherwise: the subelement index, the subelement itself.
2.obj object is not an array
The biggest difference between this method and 1 is that the fn method will be executed one by one without considering the return value. In other words, all properties of the obj object will be called by the fn method, even if the fn function returns false. The parameters passed in the call are similar to 1.
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;
}
It should be noted that the specific calling method of fn in each method is not simple. fn(i,val) or fn(args), but takes the form of fn.call(val,i,val) or fn.apply(obj.args), which means that in your own implementation of fn , you can directly use this pointer to reference the sub-elements of an array or object. This method is an implementation method used by most jQuery.
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);
};