JavaScript数组操作
函数
join(delimiter): 把数组中各个元素使用分隔符(delimiter)拼成字符串
concat(array1, array2, ...): 合并数组,对原数组不影响,只是返回合并后的新数组
pop(): 删除并返回最后一个元素
push(element1, element2, ...): 在数组末尾追加元素
shift(): 删除并返回第一个元素
unshift(element1, element2, ...): 在数组开始位置添加元素
reverse(): 将数组元素顺序首尾反转
sort(function): 给数组排序
如果不给参数,默认按字符排序(所有元素是数字也不会按数字排序的)
参数必须是一个函数,类似function(a, b) {},在函数中判断a, b的大小,a>b返回正数,a<b返回负数,a=b返回0
slice(start, end): 返回一个新的数组,将start开始,到end结束(不包括end)之间的元素复制到新数组中
splice(start, count, replaceElement1, replaceElement2, ...): 删除或者替换数组元素,从start开始,对count个元素进行删除或替换
如果提供replaceElement参数则进行替换,否则进行删除操作,被替换的元素个数和replaceElements的个数不必相等
返回一个数组,包含被删除或替换掉的元素
判断是否数组的方法
关于数组转换
可以使用[].slice.call()或者Array.prototype.slice.call(),但是IE6, IE7下对DOM元素集合使用这个操作时会报错,其它浏览器(Firefox, Opera, Safari)都正常
示例代码:
grep、map
Perl语言带出来的东西,jQuery里面就用了自己的grep和map实现
grep
对数组的grep操作,指类似这样的代码:
Array newArray = grep(condition, oldArray),这个操作将对oldArray数组的每个元素进行遍历,如果当前处理元素符合条件condition,则加入到返回数组中
jQuery中的grep类似这样: function( elems, callback),elems是DOM元素集合,callback是实现selector的一些表达式函数,如果callback返回true则表明当前处理的元素符合selector表达式
map
与grep不同的是,map不进行条件判断,只是对数组中每个元素执行指定的操作,就是将一个循环过程进行改装
喜欢动态语言风格的,可以给数组加个grep和map方法,例如:
join(delimiter): 把数组中各个元素使用分隔符(delimiter)拼成字符串
concat(array1, array2, ...): 合并数组,对原数组不影响,只是返回合并后的新数组
pop(): 删除并返回最后一个元素
push(element1, element2, ...): 在数组末尾追加元素
shift(): 删除并返回第一个元素
unshift(element1, element2, ...): 在数组开始位置添加元素
reverse(): 将数组元素顺序首尾反转
sort(function): 给数组排序
如果不给参数,默认按字符排序(所有元素是数字也不会按数字排序的)
参数必须是一个函数,类似function(a, b) {},在函数中判断a, b的大小,a>b返回正数,a<b返回负数,a=b返回0
slice(start, end): 返回一个新的数组,将start开始,到end结束(不包括end)之间的元素复制到新数组中
splice(start, count, replaceElement1, replaceElement2, ...): 删除或者替换数组元素,从start开始,对count个元素进行删除或替换
如果提供replaceElement参数则进行替换,否则进行删除操作,被替换的元素个数和replaceElements的个数不必相等
返回一个数组,包含被删除或替换掉的元素
判断是否数组的方法
var arrayVar = ["aaa", "bbb", "ccc"];
var nonArrayVar = { length:4, otherAttribute:"attr" };
document.write(arrayVar.constructor==Array);
document.write("<br />");
document.write(nonArrayVar.constructor==Array);
结果是true, falsevar nonArrayVar = { length:4, otherAttribute:"attr" };
document.write(arrayVar.constructor==Array);
document.write("<br />");
document.write(nonArrayVar.constructor==Array);
关于数组转换
可以使用[].slice.call()或者Array.prototype.slice.call(),但是IE6, IE7下对DOM元素集合使用这个操作时会报错,其它浏览器(Firefox, Opera, Safari)都正常
示例代码:
(function(){
//Supported by Firefox, IE6, IE7, Opera, Safari
var argArray=[].slice.call(arguments); //arguments is not an array,
//[].slice.call() will make a new array with arguments
document.write(argArray.reverse().join(" & ")); //result: www & 2 & 1
document.write("<br />");
//Supported by Firefox, IE6, IE7, Opera, Safari
var arrayLike = { 0:"ccc", 1:1, 2:"eee", 3:8, length:4 }; //an object that looks like an object
var trueArray = [].slice.call(arrayLike, 2, arrayLike.length); //make a new array with arrayLike
trueArray.push("2008-02-12");
document.write(trueArray.join(" | ")); //result: eee | 8 | 2008-02-12
document.write("<br />");
//Supported by Firefox, Opera, Safari
var obj = document.createElement("ul");
obj.innerHTML = '<li>AAAAAA</li> <li style="display: none;">BBBBBB</li> <li>CCCCCC</li> <li>DDDDDD</li>';
var nodeList = obj.getElementsByTagName("li"); //DOMElement collections
document.write(nodeList.length + " li node found!<br />");
var nodeArray = [].slice.call(nodeList); //make a new array with nodeList
for(var i=0; i<nodeArray.length; i++){
document.write(nodeArray[i].textContent || nodeArray[i].innerText);
document.write(" $ ");
} //result: AAAAAA $ BBBBBB $ CCCCCC $ DDDDDD $
})(1,2,"www");
//Supported by Firefox, IE6, IE7, Opera, Safari
var argArray=[].slice.call(arguments); //arguments is not an array,
//[].slice.call() will make a new array with arguments
document.write(argArray.reverse().join(" & ")); //result: www & 2 & 1
document.write("<br />");
//Supported by Firefox, IE6, IE7, Opera, Safari
var arrayLike = { 0:"ccc", 1:1, 2:"eee", 3:8, length:4 }; //an object that looks like an object
var trueArray = [].slice.call(arrayLike, 2, arrayLike.length); //make a new array with arrayLike
trueArray.push("2008-02-12");
document.write(trueArray.join(" | ")); //result: eee | 8 | 2008-02-12
document.write("<br />");
//Supported by Firefox, Opera, Safari
var obj = document.createElement("ul");
obj.innerHTML = '<li>AAAAAA</li> <li style="display: none;">BBBBBB</li> <li>CCCCCC</li> <li>DDDDDD</li>';
var nodeList = obj.getElementsByTagName("li"); //DOMElement collections
document.write(nodeList.length + " li node found!<br />");
var nodeArray = [].slice.call(nodeList); //make a new array with nodeList
for(var i=0; i<nodeArray.length; i++){
document.write(nodeArray[i].textContent || nodeArray[i].innerText);
document.write(" $ ");
} //result: AAAAAA $ BBBBBB $ CCCCCC $ DDDDDD $
})(1,2,"www");
grep、map
Perl语言带出来的东西,jQuery里面就用了自己的grep和map实现
grep
对数组的grep操作,指类似这样的代码:
Array newArray = grep(condition, oldArray),这个操作将对oldArray数组的每个元素进行遍历,如果当前处理元素符合条件condition,则加入到返回数组中
jQuery中的grep类似这样: function( elems, callback),elems是DOM元素集合,callback是实现selector的一些表达式函数,如果callback返回true则表明当前处理的元素符合selector表达式
map
与grep不同的是,map不进行条件判断,只是对数组中每个元素执行指定的操作,就是将一个循环过程进行改装
喜欢动态语言风格的,可以给数组加个grep和map方法,例如:
Array.prototype.grep = function(condition, operation, inverse){
if(arguments.length<1) return [];
var tester;
if( typeof condition=="function" ) tester=condition;
else if( condition.constructor==RegExp ) tester = function(e, i) { return condition.test(e); };
else if( typeof condition=="string" )
try{
tester = eval( "false||function(e, i){ return " + condition + "; }" );
}catch(e) {
}
else tester = function(e, i) { return false; };
if(!tester) return [];
var command;
if( typeof operation=="function" ) command=operation;
else if(typeof operation=="string")
try{
command = eval( "false||function(e, i){ " + operation + "; return e; }" );
}catch(e) {
}
if(typeof command!="function") command=function(e, i) { return e; };
var result = [], match, t;
for(var i=0; i<this.length; i++){
match = tester(this[i], i);
if(match) t = command(this[i], i);
if(match && !inverse && t!=null) t.constructor==Array ? result.concat(t) : result.push(t);
else if(!match && inverse) result.push(this[i]);
}
return result;
};
Array.prototype.map = function(callback){
if(!callback || typeof callback!="function") return this;
for(var i=0; i<this.length; i++) callback( this[i], i);
return this;
};
使用示例:if(arguments.length<1) return [];
var tester;
if( typeof condition=="function" ) tester=condition;
else if( condition.constructor==RegExp ) tester = function(e, i) { return condition.test(e); };
else if( typeof condition=="string" )
try{
tester = eval( "false||function(e, i){ return " + condition + "; }" );
}catch(e) {
}
else tester = function(e, i) { return false; };
if(!tester) return [];
var command;
if( typeof operation=="function" ) command=operation;
else if(typeof operation=="string")
try{
command = eval( "false||function(e, i){ " + operation + "; return e; }" );
}catch(e) {
}
if(typeof command!="function") command=function(e, i) { return e; };
var result = [], match, t;
for(var i=0; i<this.length; i++){
match = tester(this[i], i);
if(match) t = command(this[i], i);
if(match && !inverse && t!=null) t.constructor==Array ? result.concat(t) : result.push(t);
else if(!match && inverse) result.push(this[i]);
}
return result;
};
Array.prototype.map = function(callback){
if(!callback || typeof callback!="function") return this;
for(var i=0; i<this.length; i++) callback( this[i], i);
return this;
};
var oldArray = [ 2, 7, 8, 5, 1, 9, 2, 6, 0 ];
var newArray1 = oldArray.grep("i%2==0"); //return elements with even index
var newArray2 = oldArray.grep("e%2==1"); //return elements with odd value
document.write(newArray1 + "<br />"); //result: 2,8,1,2,0
document.write(newArray2 + "<br />"); //result: 7,5,1,9
oldArray = [ "aa", "bbbb", "abcdefg", "ccccc", "111121111", "999999999" ];
var newArray3 = oldArray.grep(/(\w)\1{4,}/);
document.write(newArray3 + "<br />"); //result: ccccc,999999999
典型jQuery风格的代码:var newArray1 = oldArray.grep("i%2==0"); //return elements with even index
var newArray2 = oldArray.grep("e%2==1"); //return elements with odd value
document.write(newArray1 + "<br />"); //result: 2,8,1,2,0
document.write(newArray2 + "<br />"); //result: 7,5,1,9
oldArray = [ "aa", "bbbb", "abcdefg", "ccccc", "111121111", "999999999" ];
var newArray3 = oldArray.grep(/(\w)\1{4,}/);
document.write(newArray3 + "<br />"); //result: ccccc,999999999
var obj = document.createElement("ul");
obj.innerHTML = '<li>AAAAAA</li> <li style="display: none;">BBBBBB</li> <li>CCCCCC</li> <li>DDDDDD</li>';
document.body.appendChild(obj);
window.setInterval(function(){
//make a new aarray with DOMElement collection
var liList = obj.getElementsByTagName("li");
var liArray = [];
for(var i=0; i<liList.length; i++) liArray.push( liList[i] );
//grep for arrays example
liArray
.grep('e.style["display"]=="none"', 'e.style["display"] = "";', true)
.map(function(e, i){ e.style["display"] = "none"; });
}, 1500);
obj.innerHTML = '<li>AAAAAA</li> <li style="display: none;">BBBBBB</li> <li>CCCCCC</li> <li>DDDDDD</li>';
document.body.appendChild(obj);
window.setInterval(function(){
//make a new aarray with DOMElement collection
var liList = obj.getElementsByTagName("li");
var liArray = [];
for(var i=0; i<liList.length; i++) liArray.push( liList[i] );
//grep for arrays example
liArray
.grep('e.style["display"]=="none"', 'e.style["display"] = "";', true)
.map(function(e, i){ e.style["display"] = "none"; });
}, 1500);