01JavaScript Array操作方法

1.栈方法

push() 接受任意数量的参数,并逐个加入数组末尾,返回数组长度
pop() 移除数组最后一位,并使数组长度减一,返回删除的元素

示例:

let colors = new Array();
let count = colors.push("red", "blue");
alert(count);   //2
count = colors.push("black");
alert(count);   //3
alert(colors.pop());    //black
alert(colors.length);   //2

2.队列方法

shift() 移除数组的首位,并使数组的长度减一,返回此元素
unshift() 在数组前添加任意个元素,返回数组长度

3.转换方法

toString() 返回以","分割的字符串
valueOf() 返回原数组
toLocalString() 同toString()
join() 一个参数,改变数组元素分割符,返回新分割符的字符串

示例:

let colors =["red", "blue", "green"];
alert(colors.toString());  //red,blue,green 字符串
alert(colors.valueOf());  //red,blue,green 数组
alert(colors);  //red,blue,green
let colors =["red", "blue", "green"];
alert(colors.join("|"));  //red|blue|green 字符串

4.重排序方法

reverse() 逆序排列数组
sort() 从小到大排序数组

5.操作方法

concat() 返回一个新的数组,将参数连接到末尾
slice() 一个参数,返回该参数到末尾的所有项;两个参数,返回两个参数之间的所有项(不包括结束位置的项)

示例:

let colors = ["red", "blue", "green"];
let colors2 = colors.concat("yellow", ["black", "brown"]);
alert(colors2); //red,blue,green,yellow,black,brown
let c3 = colors2.slice(1);
let c4 = colors2.slice(1,4);
alert(c3);  //blue,green,yellow,black,brown
alert(c4);  //blue,green,yellow

猜你喜欢

转载自blog.csdn.net/weixin_42094220/article/details/82713988