//javascript 中的数组分割 var colors = ["red","green","blue"]; //alert(colors.toString()); alert(colors.join("|")); //返回结果是red|green|blue var colors = ["red","green","blue",null]; alert(colors.join("|"));//red|green|blue| //注意当数组里面有值是null或者是undefined的时候 返回的结果是以空的字符串表示的 ------------------------------------------- //数组删除和添加 var colors = ["red","green","blue"]; //alert(colors.toString()); colors.push("white","test");//返回的结果是数组的长度 alert(colors.join("|"));//结果是red|green|blue|white|test //往数组的开头添加元素 var colors = ["red","green","blue","test"]; var item = colors.unshift("first");//数组的开头添加一个元素 alert(colors.join("|"));//返回最后的数组 //删除元素 var colors = ["red","green","blue","test"]; var item = colors.pop();//返回删除的选项结果test alert(colors.join("|"));//返回最后的数组结果red|green|blue //删除开头元素 var colors = ["red","green","blue","test"]; var item = colors.shift();//删除数组的第一个选项 alert(colors.join("|"));//返回最后的数组 ------------------------------------------------- //数组顺序事例 //顺序颠倒 var colors = ["red","green","blue","test"]; colors.reverse(); alert(colors);//结果是:test,blue,green,red //数组排序 var values = [0,1,5,10,7]; values.sort(compare); alert(values); //document.writeln(values); } function compare(value1,value2){ if(value1<value2){ return 1 ; }else if(value1>value2){ return -1 ; }else return 0 ; } ----------------------------------------------------- //向数组中添加数组 concat()方法 var colors = ["color","red"]; var colors2 = colors.concat(["ccc","bbbb"],'3333',['vvccxx',['oolll','lll']]); alert(colors2);//返回结果是:color,red,ccc,bbbb,3333,vvccxx,oolll,lll //slice()方法复制数组中的元素并不会破坏之前的元素 var colors = ["color","red",'eeee','221111']; var colors2 = colors.slice(1);//从1开始进行复制 alert(colors2);//结果是:red,eeee,221111 var colors = ["color","red",'eeee','221111']; var colors2 = colors.slice(1,3);//从1开始进行复制到第3个位置结束 alert(colors2);//结果是red,eeee --------------------------------------------------------------------- //数组中删除元素 var a = [1,2,3,5,8]; var r = a.splice(0,2); //删除前2项 alert(a);//结果是3,5,8 var a = [1,2,3,5,8]; var r = a.splice(1,1,100,200); //从第2个数开始删除一项 然后插入100 200 alert(a);//结果是1,100,200,3,5,8
js常用数组操作方法简明总结
时间:2024-3-2 04:45 作者:韩俊 分类: Javascript
标签: javascript