03 Array

来源:互联网 发布:北京医科大网络教育 编辑:程序博客网 时间:2024/06/12 19:09
 
Array 转化方法 var colors =["red","blue","green"]; colors.toString(); colors.valueOf(); 栈方法 var colors = new Array(); var count = colors.push("red","green"); alert(count); count = colors.push("black"); alert(count); var item  = colors.pop(); alert(item); alert(colors.length); var colors = ["red","blue"]; colors.push("brown"); colors[3] = "black"; alert(colors.length); var item = colors.pop(); alert(item); 队列方法 shift()移除第一项并返回该项,同时长度减1,结合shift和push可以实现队列 var colors = new Array(); var count = colors.push("red","blue");  count = colors.push("black"); var item = colors.shift(); alert(item); alert(count);unshift()在数组前端添加任意项并返回新数组的长度。重排序方法reverse()翻转sort()按升序排列数组,为了实现排序,sort方法会调用数组每一个项的toString方法,然后比较得到的字符串,以确定如何排序,即使数组中每一项都是数值,sort方法比较的也是字符串。var values =[0,1,5,10,15];valuse.sort();alert(values);// 0,1,10,15,5sort()方法可以接收一个比较函数作为参数function compare(value1,value2){if(value1<value2){return -1;}else if(value1 > value2){return 1;}else {return 0;}}var values =[0,1,5,10,15];valuse.sort(compare);alert(values);// 0,1,5,10,15操作方法concat()方法:创建一个当前数组的副本,然后将接收到的参数添加到副本的尾部,然后返回新构建的数组。var colors = ["red","green","blue"];var colors2 = colors.concat("yellow",["black","brown"]);alert(colors2);//red , green,blue,yellow,black.brownslice()方法var colors = ["red","green","blue","yellow","purple"];var colors2 = colors.slice(1);var colors3 = colors.slice(1,4);alert(colors2);// green,blue,yellow,purplealert(colors3);//green,blue,yellow    (1,2,3不包含4);splice()方法:返回一个数组,数组中包含从原始数组中删除的项。删除:可以删除任意数量的项,两个参数,要删除的第一项的位置和要删除的项数。splice(0,2)会删除数组中的前两项插入:可以向指定位置插入任意数量的项,三个参数,起始位置,要插入的项数,要插入的项,splice(2,0,"red","green");会从当前数组的位置2插入red和green。替换:向指定位置插入任意数量的项,而且同时删除任意数量的项,三个参数,起始位置,要删除的项数,要插入的项,插入的项没必要和删除的项相等。splice(2,1,"red","green");会删除当前数组位置2的项,然后再从位置2插入red和greenvar colors = ["red","green","blue"];var removed = colors.splice(0,1);alert(colors);//green ,bluealert(removed);//redremoved = colors.splice(1,0,"yellow","orange");alert(colors);//green,yellow,orange,bluealert(removed);// 空数组removed = colors.splice(1,1,"red","purple");alert(colors);//green,red,purple,orange,bluealert(removed);//yellow

0 0
原创粉丝点击