js常用数组操作方法简明总结

时间:2021-05-26

//javascript 中的数组分割var colors = ["red","green","blue"];//alert(colors.toString());alert(colors.join("|")); //返回结果是red|green|bluevar 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();//返回删除的选项结果testalert(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,221111var 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,8var a = [1,2,3,5,8];var r = a.splice(1,1,100,200); //从第2个数开始删除一项 然后插入100 200alert(a);//结果是1,100,200,3,5,8

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章