js中,给我们提供了一系列操作数组的方法。下面看例子:
shift()方法:移除数组中的第一项并返回该项
push()方法:从数组末端添加项
unshift()方法:在数组的前端添加项
pop()方法:从数组末端移除项
1.push使用
let colors = new Array();//创建一个数组
let count = colors.push("yellow", "red");//push添加两项,返回修改后数组长度
console.log(count);
console.log(colors);
//2
//[ 'yellow', 'red' ]
2.pop使用
let item = colors.pop();//pop获取最后一项
console.log(item);
console.log(colors);
//red
//[ 'yellow' ]
3.shift使用
let names = new Array();
names.push("HQ", "AB", "AC", "CB");
let m = names.shift();//移除数组第一项,并且返回
console.log(m);
console.log(names);
//HQ
//[ 'AB', 'AC', 'CB' ]
4.unshift使用
names.unshift("HQ");//数组首项添加一项
console.log(names);
//[ 'HQ', 'AB', 'AC', 'CB' ]









网友评论